簡體   English   中英

告訴父組件從同一子組件中刪除子組件

[英]Tell parent component to delete child from that same child component

我有一個Angular父組件,它基於一個值創建一個包含幾個子組件的數組(例如,1個ParentComponent創建10個ChildComponents)。 ChildComponent具有顯示多個按鈕(包括刪除按鈕)的HTML。 同時使子組件刪除自身的刪除按鈕。

刪除ChildComponent之后,應該如何通知更改的父項? 刪除后,父級仍在其ChildComponents數組中包含已刪除的對象。 我看過有關使用Output EventEmitter的帖子,但是如果沒有EventEmitter,是否可以這樣做?

如果使用ngFor指令創建子組件循環,則應該能夠直接從父組件調用delete方法。 例如:

的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方法,然后使用索引來指示應刪除列表中的哪個項目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM