Angular 2:从webservice渲染角度html组件 [英] Angular 2: Rendering angular html components from webservice
问题描述
我正在寻找如何添加html,这是角度的Web服务的返回。问题是角度指令不会呈现。这里是我的源代码
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>';
}
}
component.html的代码
Code for component.html
<div id="wrapper">
<h1 appToHtml>
Hello World!
</h1>
</div>
代码有效,但[routerLink]的渲染不起作用,pleaseee hellppp !!!
the code works, but the rendering of the [routerLink] does not work, pleaseee hellppp !!!
推荐答案
通过在指令中设置innerHTML prop,您只需设置DOM和属性。但是这个内容需要通过角度来编译,以允许类角度的行为(绑定指令,实例化组件等)。
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没有像angularJS(具有$ compile)那样准备使用编译器。您需要使用第三方库,如
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
或
https://www.npmjs.com/package/ngx-dynamic模板
这些库提供了方便的示例。您应该很容易理解如何使用它们。
请注意,您不能在这样的渲染系统中使用AOT。
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.
ngx-dynamic-template的使用版本:
如果您的动态模板需要某个组件指令,则必须配置ngx-dynamic-template以导入相应的模块。
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
然后在您的appModule或SharedModule中导入ngx时
@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)
这篇关于Angular 2:从webservice渲染角度html组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!