How to remove a component dynamically in angular

前端 未结 1 1859
死守一世寂寞
死守一世寂寞 2020-12-20 21:49

I went through angular dynamically loading components. But i could not find how to remove the component dynamically.

My requirement is that the chat application loa

1条回答
  •  一整个雨季
    2020-12-20 22:26

    Use destroy() method

    Destroys the component instance and all of the data structures associated with it.

    ref:ComponentRef;
    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);
        this.ref=componentRef;
        (componentRef.instance).data = adItem.data;
    
      }
    
      removeComponent(){
       try{
           this.ref.destroy();
       }
       catch(e){
       }
      }
    

    Example:https://stackblitz.com/edit/destroy?file=src/app/ad-banner.component.ts

    0 讨论(0)
提交回复
热议问题