【问题标题】:Tell parent component to delete child from that same child component告诉父组件从同一个子组件中删除子组件
【发布时间】:2018-07-04 01:04:11
【问题描述】:

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

删除 ChildComponent 后,我​​应该如何通知父级更改?删除后,父级的 ChildComponents 数组中仍包含已删除的对象。我看过关于使用输出 EventEmitter 的帖子,但是没有 EventEmitter 是否可以做到这一点?

【问题讨论】:

  • 如果不想使用EventEmitter,可以只使用@Input将回调函数传递给子组件
  • 如何让子组件自行删除?通常组件无法控制其生命周期。通常这是家长的责任,所以EventEmitter 是最好的解决方案。
  • 你是在使用 ngFor 创建数组吗?
  • @Ben 是的,我正在使用 ngFor。

标签: angular typescript eventemitter


【解决方案1】:

如果您使用 ngFor 指令创建子组件的循环,您应该能够直接从父组件调用删除方法。例如:

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方法,然后使用索引来指示列表中的哪一项应该被删除。

【讨论】:

    猜你喜欢
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 2021-09-27
    • 2017-03-04
    • 2017-09-17
    • 2022-01-25
    • 2017-07-07
    相关资源
    最近更新 更多