首页 > 解决方案 > 为什么 viewContainerRef 没有填充多个组件实例?

问题描述

我正在阅读 Angular Fundamentals 中的文档,试图了解如何FactoryComponentResolversViewContainerRefs工作。. . 下面的代码片段来自 Angular 文档。https://angular.io/guide/dynamic-component-loader

代码循环遍历ads数组,并不断将新的加载adItems到子模板中。

我的问题是,为什么这个过程不会导致加载同一组件的多个(最终无法管理)数量的多个实例?除了loadComponent()方法之外,不应该有某种unloadingdestroying过程来防止积累太多实例吗?还是以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);
  }
}

标签: angular

解决方案


让 viewContainerRef = this.adHost.viewContainerRef; viewContainerRef.clear()

在这部分代码中,loadComponent函数检索对 adHost viewContainerRef 对象的引用并删除现有内容。因此,要回答您关于为什么viewContainerRef.createComponent不使用组件对象淹没页面的问题是因为该clear函数首先会在创建任何新组件之前破坏现有组件。


推荐阅读