Angular 5动态添加HTML内容 [英] Angular 5 adding html content dynamically

查看:634
本文介绍了Angular 5动态添加HTML内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have following angular to add dynamically loaded content:

main.html

<div class="top">
   <ng-template #main></ng-template>
</div>

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);

        })
    };

}

getDynamicRest()中,我从php服务器获取了html标记,例如:

In the getDynamicRest(), I am getting a html markup from php server such as :

 <div class="sample"> Example </div>

但是我遇到错误"Error: No component factory found for <div class="sample"> Example </div>"

任何建议将不胜感激.

推荐答案

ComponentFactoryResolver resolveComponentFactory方法接受角度组件.

The ComponentFactoryResolver's resolveComponentFactory method accepts an Angular Component.

在您的情况下,您是将HTML注入模板而不是组件.要注入HTML,请将其保存在变量中,然后使用 DomSanitizer 对其进行清理或绕过安全检查:

In your case, you are injecting HTML into your template, not a component. To inject HTML, save it in a variable and use the DomSanitizer to either sanitize it or bypass the security check:

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);
    })
  };
}

然后,在您的模板中:

<div class="top">
  <div [innerHtml]="data"></div>
</div>

这篇关于Angular 5动态添加HTML内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆