0

I am trying to dynamically create and destroy components. Let's say I have a component A which has a button on click of which I create a component B using ComponentFactoryResolver. Now I am creating multiple instance of components by clicking on the button multiple times. My component B has an html something as the following:

<div id="container-{{index}}"
    ...more content
</div>

In my component B, I want to destroy some other instance of B which was created earlier. How can I get the reference to some other instance of B inside a new instance of B? Is it possible to somehow use the id of the underlying html to get the reference to the component?

1
  • Actually you can use dependency injection to have it, you can inject your A component in your B component, this combined with a @ViewChildren(BClassComponent) bComponentsList: BClassComponent []; you gonna have a reference to all B Components that you have in your A template. But I'm sure that there would be another cleaner option depends on your specific needs. Commented Jun 7, 2018 at 18:05

1 Answer 1

1

I would do what the commenter Ricardo suggested and use dependency injection.

Somewhere inside component A add a method that will be called by each child component B in their ngOnInit...

 componentList : any[] = [];

 addChild(component: any) { 
    this.componentList.push(component)
 }

Then inside the child components, inject the parent into their constructor and call the add method in the ngOnInit so the parent maintains an array of every instance of component B

 constructor( private parent: ComponentA) {}

 ngOnInit() { this.parent.addChild(this); } 

Now from any B component you could access the parent components public 'componentList' property to see all the created instances. Don't forget to import ComponentA inside the ComponentB files

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

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.