【问题标题】:How to destroy "self" component programatically in angular2?如何在 angular2 中以编程方式销毁“自我”组件?
【发布时间】:2017-03-18 20:42:25
【问题描述】:

我有多个组件,每个组件中都有一个“销毁”按钮,在以下示例中,此按钮将有 4 个实例:

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

我可以在组件的“destroy”函数中添加什么,使其仅销毁被点击的“mycomponent”实例?

【问题讨论】:

    标签: angular


    【解决方案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。但只要你的组件发出一个你的容器可以监听的事件,都是一样的。

    【讨论】:

    • 是的,这就是要走的路
    猜你喜欢
    • 2021-08-13
    • 2017-09-02
    • 2019-05-19
    • 1970-01-01
    • 2017-11-20
    • 2018-02-22
    • 2017-01-21
    • 1970-01-01
    • 2016-05-26
    相关资源
    最近更新 更多