告诉父组件从同一子组件中删除子组件

时间:2018-01-24 21:17:49

标签: angular typescript eventemitter

我有一个Angular父组件,它根据一个值创建一个包含多个子组件的数组(例如,1个ParentComponent创建10个ChildComponents)。 ChildComponent具有显示多个按钮的HTML,包括删除按钮。删除按钮同时使子组件自行删除。

删除ChildComponent后,我该如何通知更改的父级?删除后,父级仍在其中包含已删除的对象的ChildComponents数组。我已经看过有关使用Output EventEmitter的帖子,但是没有EventEmitter可以这么做吗?

1 个答案:

答案 0 :(得分:2)

如果使用ngFor指令创建子组件循环,则应该能够直接从父级调用de​​lete方法。例如:

HTML

<div *ngFor="let item of items; index as i;">
  <div>{{name}}</div>
  <button (click)="delete(i)"></button>
</div>

组件

import { Component } from "@angular/core";

@Component({
  selector: "app",
  templateUrl: "./app.html",
})
export class AppComponent {    
  public items = [{name: "first"}, {name: "second"}];

  public delete(index: number) {
    this.items.splice(index, 1);
  }
}

每个子组件可以直接从父组件调用delete方法,然后使用索引指示应该删除列表中的哪个项目。

相关问题