angular - 使用不同的数据多次加载动态组件
问题描述
我需要多次加载一个动态组件并根据某个值动态传递数据,以便它将加载运行时数据。
我试过下面的例子 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 中动态传递不同的“消息”值。
解决方案
这是我的方法:
- 在您的模板中,为所有消息创建一个容器
<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;
});
}
推荐阅读
- html - 如何阻止横幅与其他内容重叠?
- c# - C#:多个类实例都做同样的事情
- firebase - Flutter Firestore 查询嵌套子集合
- apache-spark - 在 pySpark 中解析无效的 JSON
- kubernetes - http:代理错误:x509:证书由未知权威签署
- apache-camel - Camel ProducerTemplate requestBody 和返回类型
- winapi - 获取音频设备的图标
- r - 在 Tidyverse 中过滤事件数据的时间
- python - 在我的 SQL Server 数据库中存储 TimeDelta
- android - 在 viewpager 片段的 recyclerview 中插入原生广告