Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 !!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
244 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...