angular - 为什么 viewContainerRef 没有填充多个组件实例?
问题描述
我正在阅读 Angular Fundamentals 中的文档,试图了解如何FactoryComponentResolvers
和ViewContainerRefs
工作。. . 下面的代码片段来自 Angular 文档。https://angular.io/guide/dynamic-component-loader。
代码循环遍历ads
数组,并不断将新的加载adItems
到子模板中。
我的问题是,为什么这个过程不会导致加载同一组件的多个(最终无法管理)数量的多个实例?除了loadComponent()
方法之外,不应该有某种unloading
或destroying
过程来防止积累太多实例吗?还是以destroying
某种方式发生在幕后?还是viewContainerRef.createComponent(componentFactory)
足够聪明地知道如果它已经创建了一个组件,它会简单地返回对该现有组件的引用而不是创建一个新组件?非常感谢,如果有人可以请澄清!
export class AdBannerComponent implements OnInit, OnDestroy {
@Input() ads: AdItem[];
currentAdIndex = -1;
@ViewChild(AdDirective) adHost: AdDirective;
interval: any;
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
ngOnInit() {
this.loadComponent();
this.getAds();
}
ngOnDestroy() {
clearInterval(this.interval);
}
loadComponent() {
this.currentAdIndex = (this.currentAdIndex + 1) % this.ads.length;
let adItem = this.ads[this.currentAdIndex];
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);
let viewContainerRef = this.adHost.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
(<AdComponent>componentRef.instance).data = adItem.data;
}
getAds() {
this.interval = setInterval(() => {
this.loadComponent();
}, 3000);
}
}
解决方案
让 viewContainerRef = this.adHost.viewContainerRef; viewContainerRef.clear()
在这部分代码中,loadComponent
函数检索对 adHost viewContainerRef 对象的引用并删除现有内容。因此,要回答您关于为什么viewContainerRef.createComponent
不使用组件对象淹没页面的问题是因为该clear
函数首先会在创建任何新组件之前破坏现有组件。
推荐阅读
- dll - 在 RAD Studio 的命名空间下调用 DLL 函数
- python - 为什么 to_numeric() 将 str 转换为 float 而不是 int?
- sql - 如何按周报表创建交易表?
- python - 如何循环遍历python中的大型嵌套列表?
- java - Presto JDBC 大查询极慢
- git - 使用 git 设置开发环境但不加载引导程序和字体真棒
- pandoc - 尝试在 circleci 构建脚本中下载最新版本的 pandoc
- javascript - 如何使用 Ajax 将参数传递给模态表单
- python - 刚刚使用 Anaconda 安装了 Jupyter,但无法使用终端运行它。说找不到命令
- mysql - MySQL选择并匹配两个表并根据匹配的数据更新列