Angular 2: Rendering angular html components from

2019-09-21 11:11发布

问题:

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.directive.ts

import { Directive, ElementRef, OnInit } from '@angular/core';
@Directive({
  selector: '[appToHtml]'
})
export class ToHtmlDirective {
constructor( private el: ElementRef) {}


tohtml() {
  //it is assumed that this is the return of the webservice
  this.el.nativeElement.innerHTML = '<a 
  [routerLink]="/link/to/page">helpful!
   </a>';
  }
}

Code for component.html

<div id="wrapper">

<h1 appToHtml>
  Hello World!
</h1>
</div>

the code works, but the rendering of the [routerLink] does not work, pleaseee hellppp !!!

回答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>


回答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