0

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?

Cpt.Kitkat
  • 120
  • 4
  • 17

2 Answers2

1

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

Ehsan Kiani
  • 3,050
  • 1
  • 17
  • 19
  • It removes all the component at one go... I want to be able to remove one by one ...suppose i click add component button 3 times then remove button should remove 1 form first then another and so on.... – Cpt.Kitkat Apr 15 '19 at 06:16
0

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

Daniel Piñeiro
  • 3,009
  • 1
  • 16
  • 26