简体   繁体   中英

Angular - How a destroy a Dynamically component by a button click

I am using this to dynamically create a component in angular:

addComponent() {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
    const viewContainerRef = this.injectComp.viewContainerRef;
    const compRef = viewContainerRef.createComponent(componentFactory);
    compRef.instance.someProperty = "some data";
}

So each time the method is executed a new instance of the component is created. Up to there, all is great but my question is:

How do I destroy these created components from the ChildComponent itself with a button click event?

1) You can keep track of component or all component in a variable or in a object and destroy them:-

2) Or, destroy previous component when loading new one in DOM by storing last reference and .destroy() them before inserting new one.

.html

 <ng-container #dynamicComponentContainer id="dynamicComponentContainer"></ng-container>

.ts

         let componentRef = this.componentFactoryResolver.resolveComponentFactory(cmptName).create(this.injector);

                // check for duplicates and update with new one
             //   this.checkForDuplicateCmp(componentRef);

                componentRef.instance['inputdata'] = initCmpInputdata;
                let indexView = this.dynamicComponentContainer.length;
                this.dynamicComponentContainer.insert(componentRef.hostView, indexView);

      // keep refrence of lastComponent added to DOM
            this.lastComponent = componentRef;


  public remove component(){
    // destroy components as on click
      this.lastComponent.destroy();
     //or
     for (var j = 1; j < this.dynamicComponentContainer.length; j++) {
          this.dynamicComponentContainer.remove(j);  //or pass j 
      }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM