2016-11-04 63 views
0

我有多个组件,每个组件有一个按钮,上面写着“消灭”,在下面的例子中,就不会有这个按钮的4个实例:如何在angular2中以编程方式销毁“self”组件?

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

我可以把什么在“消灭”该组件的功能是否仅销毁点击“mycomponent”的实例?

回答

1

一种可能的选择:您可以定义应在容器的视图模型中与其数据一起显示的组件。该视图只是将所有组件全部渲染为一个数组。需要删除的组件发出容器捕获的事件。这会触发容器代码从需要呈现的组件列表中删除组件。

视图模型:

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

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

模板:

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

这个例子使用的,而不是myComponent的一个按钮。但只要你的组件发出一个事件,你的容器就可以听到它是一样的。

+0

是的,这是要走的路 – Aesdotjs