1

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?

8
  • Self close means -- you want to destroy the components ? Commented Jun 30, 2019 at 9:22
  • Yes, if I create 5 components (for example) ... I want to be able to click on a button on the component and self destroy it Commented Jun 30, 2019 at 9:23
  • Check this stackoverflow link Commented Jun 30, 2019 at 9:24
  • Possible duplicate of How to remove a component dynamically in angular 6 Commented Jun 30, 2019 at 9:25
  • This is not how I want to do it. I want to trigger a self destroy on the childComponent itself. Can it be done? Commented Jun 30, 2019 at 9:27

1 Answer 1

2

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 
      }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.