Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

javascript - 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.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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...