【问题标题】:Load dynamic component multiple times with different data使用不同的数据多次加载动态组件
【发布时间】:2020-01-13 10:51:50
【问题描述】:

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

我试过下面的例子 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中动态的“message”的不同值。

【问题讨论】:

  • 所以您希望message 属性的值在每次更改时在动态组件中更新您是否希望使用不同的“消息”生成多个动态组件?
  • 我想要使用不同的“消息”生成多个动态组件,我们可以在任何点击事件上更新消息的值

标签: angular typescript angular-dynamic-components


【解决方案1】:

这是我的方法:

  • 在您的模板中,为所有消息创建一个容器
<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;
   });
 }

Here is a StackBlitz demo.

【讨论】:

  • 我尝试使用comp.changeDetectorRef.detectChanges();,但它会停止循环,因此不会创建其他组件
猜你喜欢
  • 2016-09-04
  • 1970-01-01
  • 2018-03-13
  • 2020-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-01
  • 2020-10-07
相关资源
最近更新 更多