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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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....
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.