How to remove a component dynamically in angular

ⅰ亾dé卋堺 提交于 2019-11-29 14:41:26

Use destroy() method

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

ref:ComponentRef<any>;
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;
    (<AdComponent>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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!