2017-05-03 66 views
-1

我有一個父母組件,其中列表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尚未更新。

如何從transactions

列表中刪除此transaction(我敢肯定,它與@Output做我只是感到非常熟悉如何使用它。)

回答

2

使用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> 

終於在你的父組件拼接交易陣列:

... 

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

更先進的方法是使用服務,既組件共享。哪種方法更好?取決於複雜性。問候 –