我有以下角度来添加动态加载的内容:
main.html中
<div class="top">
<ng-template #main></ng-template>
</div>
Run Code Online (Sandbox Code Playgroud)
main.ts
import { Component, ViewChild, ComponentFactoryResolver, ViewContainerRef } from '@angular/core';
@Component({
selector: 'page-main_page',
templateUrl: 'main_page.html'
})
export class main_page {
@ViewChild('main', { read: ViewContainerRef }) entry: ViewContainerRef;
data: any;
constructor(public resolver: ComponentFactoryResolver){
};
ngOnInit(){
this.getDynamicREST().then((res)=>{
this.data = res; //Where it is a html markup from php server: <div class="sample"> Example </div>
const factory = this.resolver.resolveComponentFactory(this.data);
this.entry.createComponent(factory);
})
};
}
Run Code Online (Sandbox Code Playgroud)
在getDynamicRest(),我从PHP服务器获得一个HTML标记,如:
<div class="sample"> Example </div>
Run Code Online (Sandbox Code Playgroud)
但是我收到了一个错误 "Error: No component factory found for <div class="sample"> Example </div>"
任何建议将不胜感激.
vin*_*nce 27
所述ComponentFactoryResolver的resolveComponentFactory方法接受的角度成分.
在您的情况下,您将HTML注入模板,而不是组件.要注入HTML,请将其保存在变量中,然后使用它DomSanitizer来清理它或绕过安全检查:
export class main_page {
data: SafeHtml;
constructor(private sanitizer: DomSanitizer) {}
ngOnInit(){
this.getDynamicREST().then((res)=> {
this.data = this.sanitizer.sanitize(res);
/* OR */
this.data = this.sanitizer.bypassSecurityTrustHtml(res);
})
};
}
Run Code Online (Sandbox Code Playgroud)
然后,在您的模板中:
<div class="top">
<div [innerHtml]="data"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21075 次 |
| 最近记录: |