简体   繁体   中英

How to destroy “self” component programatically in angular2?

I have multiple components, in each component there is a button that says "destroy", in the following example, there would be 4 instances of this button:

<div class="container">
<mycomponent></mycomponent>
<mycomponent></mycomponent>
<mycomponent></mycomponent>
<mycomponent></mycomponent>
</div>

What can I put in the "destroy" function of the component such that it destroys only the instance of "mycomponent" that is clicked?

One possible option: You define the components that should be shown together with their data in the viewmodel of your container. The view just renders all all components as an array. The component that needs to be removed emits an event that is captured by the container. This triggers the containers code to remove the component from the list of components that need to be rendered.

ViewModel:

components = [{
  id: "a",
  val: 5
}, {
  id: "b",
  val: 7
}];

removeComponent(id) {
  this.components = this.components.filter(e => e.id != id);
}

Template:

<div *ngFor="let component of components">
    <button (click)="removeComponent(component.id)">
        Remove {{component.val}}
    </button>
</div>

This example uses a button instead of mycomponent. But as long as your component emits an event that your container can listen on it's the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM