Angular 5动态添加html内容

ste*_*Kim 9 angular

我有以下角度来添加动态加载的内容:

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

所述ComponentFactoryResolverresolveComponentFactory方法接受的角度成分.

在您的情况下,您将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)

  • 清理应该使用 `this.sanitizer.sanitize(SecurityContext.HTML, res)` (2认同)
  • 你知道吗,我们如何动态注入 html(具有绑定)。绑定值如何表示。目的是使绑定与组件中的属性一起工作。 (2认同)