删除子项并更新父列表

时间:2017-05-03 18:59:37

标签: angular angular2-template

我有一个父组件,其列表为transactions。它们显示如下:

<table class="table awaken-table">
    <thead>
        <tr>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <transaction-row style="display:table-row;line-height:32px;" *ngFor="let transaction of transactions | orderDate" [transaction]="transaction"></transaction-row>
    </tbody>
</table>

...... transaction-row看起来像这样:

@Component({
    selector: 'transaction-row',
    template: `
            <td text-center style="font-size:16px">
                <i class="fa fa-trash danger" style="font-size:20px;" (click)=deleteAlert()></i>
            </td>
    `
})

export class TransactionRow {
    @Input() transaction: any;

    ...
}

当我点击图标并致电deleteAlert()时,我成功删除了该项目,但由于transactions尚未更新,因此该项目仍保留在列表中。

如何从transaction

列表中删除此transactions

(我确定它与@Output有关。我对如何使用它非常不熟悉。)

1 个答案:

答案 0 :(得分:2)

在子Component中使用EventEmitter,如下所示:

import { Input, Output, Component, EventEmitter } from '@angular/core';

@Component({
    selector: 'transaction-row',
    template: `
            <td text-center style="font-size:16px">
                <i class="fa fa-trash danger" style="font-size:20px;" (click)=deleteAlert()></i>
            </td>
    `
})

export class TransactionRow {
    @Input() transaction: any;
    @Output() deleteRow: EventEmitter<any> = new EventEmitter<any>();
    ...

    deleteAlert(){
      ...
      this.deleteRow.emit(this.transaction);
    }
}

在html中听deleteRow事件

<transaction-row style="display:table-row;line-height:32px;" *ngFor="let transaction of transactions | orderDate" [transaction]="transaction" (deleteRow)="onDeleteRow($event)"></transaction-row>

最后在您的父组件splice transactions数组中:

...

   onDeleteRow(item: any) {
       this.transactions.splice(this.transactions.indexOf(item),1);
   }
...