Why is viewContainerRef not filling up with multiple instances of components?

Discussão em 'Angular' iniciado por Crowdpleasr, Março 16, 2025.

  1. Crowdpleasr

    Crowdpleasr Guest

    I'm going through the documentation in Angular Fundamentals, trying to understand how FactoryComponentResolvers and ViewContainerRefs work . . . The code snippet below is from the Angular documentation. https://angular.io/guide/dynamic-component-loader.

    The code cycles through the ads array, and continually loads new adItems into the child template.

    My question is, why doesn't this process lead to multiple (eventually unmanageable) numbers of multiple instances of the same component being loaded? Alongside the loadComponent() method, shouldn't there be some kind of unloading or destroying process to prevent too many instances getting accumulated? Or does the destroying somehow occur behind the scenes? Or is viewContainerRef.createComponent(componentFactory) smart enough to know that if it's already created a component, it will simply return a reference to that existing component rather than creating a new one?

    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);
    }
    }

    Continue reading...

Compartilhe esta Página