首页 > 解决方案 > 使用不同的数据多次加载动态组件

问题描述

我需要多次加载一个动态组件并根据某个值动态传递数据,以便它将加载运行时数据。

我试过下面的例子 https://dzone.com/articles/how-to-dynamically-create-a-component-in-angular

根据示例,我们有一个具有“消息”属性的 messageComponent,在 hostComponent 中,我们在 html 文件中添加一个模板,例如

<div style="text-align:center">
     <h1>
         Welcome to {{ title }}!
     </h1>
     <template #messagecontainer>
     </template>
 </div>

所以在模板标签的地方,我们的 messageComponent 将被替换。

我需要一些东西,比如我们可以多次迭代这个模板,并在 messageComponent 中动态传递不同的“消息”值。

标签: angulartypescriptangular-dynamic-components

解决方案


这是我的方法:

  • 在您的模板中,为所有消息创建一个容器
<ng-container #messageContainer></ng-container>
  • 添加一个函数,允许我们创建一个组件并将其插入到视图中
private createComponent (compClass) {
   const compFactory = this.cfr.resolveComponentFactory(compClass);

   return this.messageContainer.createComponent(compFactory);;
 }
  • 根据传入的数据多次加载组件;我们还将跟踪已加载的组件,以便在我们需要加载另一个动态组件时能够销毁它们。
 private loadNewComponentList () {
   this.messages.forEach((msg, idx) => {
     this.destroyCompFromList(this.componentList[idx]);

     const comp = this.createComponent(componentMap[this._crtComp]);

     (comp.instance as any).message = msg;

     comp.changeDetectorRef.detectChanges();

     this.componentList[idx] = comp;
   });
 }

这是一个 StackBlitz 演示


推荐阅读