Skip to content Skip to sidebar Skip to footer

Angular 2: Rendering Angular Html Components From Webservice

I am looking for how to add html which is a return of the web service, in angular. The problem is that the angular directives do not rendered. here is my source code //tohtml.direc

Solution 1:

By setting innerHTML prop in your directive you only set DOM and attributes. But this content need to be compile by angular to allow angular-like behavior (binding directives, instanciating components etc..) .

Angular dont have compiler ready to use like angularJS ( which has $compile ). You need to use 3rd party libraries like

https://www.npmjs.com/package/p3x-angular-compile

or

https://www.npmjs.com/package/ngx-dynamic-template

Those lib comes with handy examples. You should easily understand how to use them. Be aware that you cant use AOT with such a rendering system.

Edition for ngx-dynamic-template usage :

if your dynamic templates need some directive of component, you have to configure ngx-dynamic-template to import the corresponding modules.

You can create a dynamic module like that in your case

@NgModule({
    imports: [
        RouterModule
    ],
    exports: [
        RouterModule
    ]
})

export class DynamicModule {}

and then when importing ngx in your appModule or SharedModule

@NgModule({
    imports: [
        ...
        NgxDynamicTemplateModule.forRoot({extraModules: [DynamicModule]})
        ...
    ],

Then you will be able to use routerLink without problem (i just tested)

in cmpt : 
htmlTemplate = `<a [routerLink]="['dress-options']">link to user component</a>`;

in template : 
<div dynamic-template [template]="htmlTemplate"></div>

Solution 2:

With the latest angular version for me only this module works fine: https://www.npmjs.com/package/ngx-dynamic-template v2.1.24 for angular4, v.2.3.0 is for angular5


Post a Comment for "Angular 2: Rendering Angular Html Components From Webservice"