Angular 5动态添加html内容

时间:2018-02-21 18:50:39

标签: angular

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

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标记,例如:

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

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

我们非常感谢任何建议。

3 个答案:

答案 0 :(得分:17)

ComponentFactoryResolverresolveComponentFactory方法接受角度组件。

在您的情况下,您将HTML注入模板,而不是组件。要注入HTML,请将其保存在变量中,然后使用DomSanitizer对其进行清理或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>

答案 1 :(得分:0)

有一个新的库可以完成这项工作。它称为ngx-dynamic-hooks。链接here

使用此工具,您不必禁用AOT(与ngx-dynamic-template一样,链接here)。

答案 2 :(得分:-4)

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