使用不同的数据多次加载动态组件
Load dynamic component multiple times with different data
我需要多次加载动态组件并根据某个值动态传递数据,以便它加载运行时数据。
我试过下面的例子
https://dzone.com/articles/how-to-dynamically-create-a-component-in-angular
根据示例,我们有一个具有 "message" 属性 和
在 hostComponent 中,我们在 html 文件中添加一个模板,如
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
<template #messagecontainer>
</template>
</div>
因此我们的 messageComponent 将替换模板标签。
我需要类似我们可以多次迭代此模板并通过
"message" 在 messageComponent.
中动态的不同值
这是我的方法:
- 在您的模板中,为所有消息创建一个容器
<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;
});
}
我需要多次加载动态组件并根据某个值动态传递数据,以便它加载运行时数据。
我试过下面的例子 https://dzone.com/articles/how-to-dynamically-create-a-component-in-angular
根据示例,我们有一个具有 "message" 属性 和 在 hostComponent 中,我们在 html 文件中添加一个模板,如
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
<template #messagecontainer>
</template>
</div>
因此我们的 messageComponent 将替换模板标签。
我需要类似我们可以多次迭代此模板并通过 "message" 在 messageComponent.
中动态的不同值这是我的方法:
- 在您的模板中,为所有消息创建一个容器
<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;
});
}