ng-dynamic
Dynamic Content Projection in Angular 2+
$ npm install --save ng-dynamic
Live Demo: Plunker
'dynamic' means...
We often need to project some dynamic contents into your Angular app. For example, if you make a markdown editor, you want to display the rendererd preview.
This code has some problems:
[innerHTML]
will sanitize its value and strip some elements.- in innerHTML, any Angular components like
<my-button>
don't work.
ng-dynamic can solve these problems by using standard Angular APIs and some hacks.
<dynamic-html [content]="html">
<dynamic-html>
is a component to render given HTML string and mount components in the HTML.
Example:
Result:
Awesome Document bla bla bla Click Me
<my-button>
is resolved as MyButtonComponent
.
DynamicHTMLModule
To use <dynamic-html>
, you have to import DynamicHTMLModule
with forRoot
static method.
Its argument is a DynamicHTMLOptions
object:
/** * defines dynamic-projectable components * * ```ts * @Component({ * selector: 'child-cmp', * template: `<p>child:{{text}}</p>`, * }) * class ChildCmp { * @Input() text: string; * } * * DynamicHTMLModule.forRoot({ * components: [ * { component: ChildCmp, selector: 'child-cmp' } }, * ] * }) * ``` */ /** * options for DynamicHTMLModule */
OnMount
Lifecycle method
/** * Lifecycle hook that is called after instantiation the component. * This method is called before ngOnInit. */
OnMount
allows you to create component has hybrid content projection.
hybrid content projection means that the component can project its content from even static template or dynamic HTML.
See also demo.
<dynamic-html>
Constraints
[content]
is not a template. so it cannot resolve{{foo}}
,*ngIf
and any template syntax.
*dynamicComponent="template"
dynamicComponent
is a directive to create dynamic component which has the template.
Example:
Result:
Awesome Document foo Click Me
<my-button>
is resolved as MyButtonComponent
.
DynamicComponentModule
To use dynamicComponent
, you have to import DynamicComponentModule
with forRoot
static method.
Its argument is a NgModule
metadata object:
/** * Setup for DynamicComponentDirective * * ```ts * @NgModule({ * imports: [ * DynamicComponentModule.forRoot({ * imports: [CommonModule] * }) * ], * }) * class AppModule * ``` */
dynamicComponent
Constraints
dynamicComponent
needs JitCompiler
. You can use AoT compilation, but you cannot eliminate the dependency on @angular/compiler
.
; // reflect-metadata polyfill; ;;; platformBrowser.bootstrapModuleFactoryAppModuleNgFactory;
License
MIT
Developing
npm i && npm run demo # and open http://localhost:8080
Contributions welcome!