How to Dynamically Remove component in ComponentResolveFactory

I am referring to this Stackblitz example to create forms dynamically and call them using componentFactoryResolver. However, I also need a button to remove the added form. Suppose user clicks on button then form is added and if he clicks again another form is added.So I need to provide a button to remove form. How can I achieve that?

2 answers

  • answered 2019-04-15 06:11 Ehsan Kiani

    create a method like this

     removeComponent() {
        this.container.clear();
      }
    

    UPDATE: to remove an specific component use this:

    First create a component array

      components = [];
    

    then

       add(): void {
    
        // create the component factory
        const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
    
        // add the component to the view
        const componentRef = this.container.createComponent(componentFactory);
    
     this.components.push(componentRef );
        // pass some data to the component
        componentRef.instance.index = this._counter++;
      }
    
    
      removeComponent(componentIndex ) {
    
          // Remove component from both view and array
          this.container.remove(componentIndex );
           this.components.splice(componentIndex, 1);
    
    
      }
    

    hope it helps

  • answered 2019-04-15 06:29 Daniel Piñeiro

    I did a fork of your example:

    https://stackblitz.com/edit/angular-dynamic-components-stack-55683353?file=src/app/app.component.ts

    I added a button with an output in the dynamic component to destroy it with this code:

    componentRef.instance.onRemove.subscribe(() => {
      componentRef.destroy();
    });
    

    There is some examples on how to do it here too: Dynamically ADDING and REMOVING Components in Angular