0

I am creating a component at runtime using ComponentFactoryResolver.

This method adds the component

addComp(): void {
  const componentFactory = this.componentFactoryResolver.resolveComponentFactory(OneComponent);
  const viewContainerRef = this.injectComp.viewContainerRef;
  viewContainerRef.createComponent(componentFactory);
}

And this method delete's a component

removeComp(): void {
  const viewContainerRef = this.injectComp.viewContainerRef;
  viewContainerRef.remove();
}

The issue I'm having is that I need to be able to tell it which component I want to remove as it seems to just delete each component in the order it's created.

How can I modify the removeComp() method so that I can define the component that I want to remove?

teumec
  • 65
  • 1
  • 6

1 Answers1

1

Keep track of list of generated components for removal purposes

 components = [];

In addComp() Push the component so that we can keep track of which components are created. You will need to pass class instance to it (componentClass: Type)

 const component = this.injectComp.viewContainerRef.createComponent(componentFactory);
 this.components.push(component);

In removeComp(), Find the component and remove component from both view and array. You will need to pass class instance to it (componentClass: Type)

 const component = this.components.find((component) => component.instance instanceof componentClass);
 const index = this.components.indexOf(component);

 if (index!== -1) {
      this.injectComp.viewContainerRef.remove(this.injectComp.viewContainerRef.indexOf(component));
      this.components.splice(index, 1);
    }
Tejeshree
  • 942
  • 6
  • 9