首页 > 解决方案 > Angular 10:如何创建动态组件/html?

问题描述

2个问题:

  1. <div>{{ someData }}</div>- 如何使{{ someData }}转换为html?
  2. <div>{{ MyComponentClass }}</div>- 如何使它创建组件MyComponentClass 的实例并将其放入div 中?

对于问题 1,我想我需要一种方法来访问 DOM 元素,然后自己注入它。对于问题 2,我不知道,但它会非常有用。

标签: htmlangulardynamiccomponents

解决方案


  1. 问题:

您可以将字符串/html 变量绑定到 [innerHTML] 属性绑定。

<div [innerHTML]="theHtmlString"></div>

如果 html 不起作用,您需要注入 DomSanitizer 来告诉 Angular html 是安全的。

 constructor(private sanitizer:DomSanitizer) {
    this.htmlString = this.sanitizer.bypassSecurityTrustHtml(style);
  }
  1. 问题:

您可以使用 @ViewChild 动态创建组件并从您的 div 获取 ViewContainerRef 并使用 componentFactoryResolver:

模板:

<div #yourdiv></div>

零件:

@ViewChild("yourdiv" , {read: ViewContainerRef}) private vcr: ViewContainerRef;
   
constructor(private componentFactoryResolver: ComponentFactoryResolver) {

    let resolver = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
    let componentFactory =  this.vcr.createComponent(resolver);
  
  }

推荐阅读