Angular 5动态添加HTML内容

25

我需要将动态加载的内容添加到以下 Angular 中:

main.html

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

main.ts

(主程序.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 标记,例如:

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

然而,我遇到了一个错误 "Error: No component factory found for <div class="sample"> Example </div>"

希望能得到任何建议。

3个回答

53

ComponentFactoryResolverresolveComponentFactory 方法接受一个 Angular 组件。

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

然后,在您的模板中:

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

2
应使用this.sanitizer.sanitize(SecurityContext.HTML, res)来进行清理。 - Pipo
2
你知道我们如何动态注入具有绑定的HTML吗?绑定的值是如何表示的?目的是使绑定与组件中的属性一起工作。 - Darey
1
我认为这种方法不适合Angular组件或指令。例如:<my-component></..><div [myDirective]="something"> - Sh eldeeb
1
@Saad 但是根据我所读的,为了让绑定工作,我需要声明输入和输出。但我不知道它们是什么。我的情况是,我有一个用户创建的项目列表,可以添加用户想要添加的任何属性,当选择其中一个时,在右侧我需要显示详细信息。详细信息来自后端的html,使用绑定构建,并在另一个调用中需要绑定的数据。你有什么建议吗? - bokkie
@bokkie 这个有更新了吗?有可用的解决方案吗? - Revathi Sekar
显示剩余6条评论

2
有一个新的库可以完成这个工作,叫做“ngx-dynamic-hooks”。链接在这里
使用这个库时,您不需要禁用AOT(就像使用“ngx-dynamic-template”一样,链接在这里)。

-6
             let transporter = nodemailer.createTransport({
      host :'smtp.gmail.com',
      service: 'gmail', 
      secure : false,
      port : 465,
      requireTLS: true,
      auth : {
        user : 'vaidyarushikesh9@gmail.com',
        pass : 'PAssword', 
      }
    });     


             var email = req.body.email`enter code here`;
            let htmlContent = `<h1><strong>Foreget Password Link Form</strong></h1>
            <p>Hi,</p>
   <p>http://localhost:4200/forget/${email} contacted with the following Details</p>`;

      let mailoptions = {
      from : 'vaidyarushikesh9@gmail.com',
      to : req.body.email,
      subject : 'tesst',
      text: '',
      html: htmlContent
    };
      transporter.sendMail(mailoptions,function(err,data){
        if(err){
          console.log('errr',err)
        }else{
          console.log('email send');
        }
      });

3
虽然这段代码可能解决了问题,但是在回答中加入解释说明如何以及为什么能够解决该问题,将有助于提高您的回答质量并可能获得更多的赞同。请记住,您正在为未来的读者回答问题,而不仅仅是回答当前提问者的问题。请编辑您的答案,添加解释并指出适用的限制和假设。 - Adrian Mole

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接