I would like to know if is possible to do something like the following in Angular 2. Having a component with this template (for example):
ParentComponent template
<div>
<childOne></childOne>
<childTwo *ngFor="let item of items">
whatever
</childTwo>
</div>
Is there any way to remove these items using the ViewContainerRef from the ParentComponent, like the following?
var viewContainerRef = /* get ParentComponent ViewContainerRef */
var index = viewContainerRef.indexOf(childViewRef);
viewContainerRef.remove(index);
I tried using a solution similar to the one proposed here to retrieve the child ViewRef: Angular2 , How to find index of a view inside a viewContianer
But the indexOf is returning -1, as if the child ViewRef is not present in the container.
I wanted to remove these child components outside of ParentComponent, not inside the ParentComponent code, like removing from the items array or through bindings.
I tried using the destroyView method from the Renderer also, but with no effect. The NgFor is iterating through the items array and creating embedded views for each childTwo, I don't if, in this case, the ViewRef obtained from ChildTwo injector (as proposed in the link solution) is the same as these EmbeddedViewRef.
Is there any way to do something like that?
Thank you.
*********************** UPDATE ***************************
I will try to simplify a little what I am trying to achieve. I am developing a dashboard where the user can create its components using an API like the following:
@Component({ selector: 'child' })
class UserChildComponent extends DashboardComponent {
(...)
}
@Component({ selector: 'parent' })
class UserParentComponent extends DashboardComponent {
@ViewChildren(UserChildComponent) m_children: QueryList<UserChildComponent>;
private models: Array<ChildModel>;
(...)
}
/* UserParentComponent template
<div>
<child></child>
<child *ngFor="let model of models"></child>
</div>
I have a logical tree of all the Dashboard components and its relationships with one another (parent/child), because of the subtyping and other stuff behing the scenes that doesn't concern here.
This is the scenario I am thinking of: the user would be able to remove any of these child dashboard components. I would like to, having all the relationship tree needed, remove the child from the parent and notify the user (maybe through the ViewChildren in the parent). Or I could actually call a method on the parent, so that the user could update its models Array, maybe would be the best way.
I was just thinking of a way that the user would have the less work possible, not having to worry about synchronizing the model\component (in this case)
Thanks again.