天天看點

Angular應用裡child Component如何向parent Component發送事件

detail Component裡,使用event binding,給button click事件注冊一個處理函數delete:

<img src="{{itemImageUrl}}" [style.display]="displayNone">
<span [style.text-decoration]="lineThrough">{{ item.name }}
</span>
<button (click)="delete()">Delete</button>      
@Output() deleteRequest = new EventEmitter<Item>();

delete() {
  this.deleteRequest.emit(this.item);
  this.displayNone = this.displayNone ? '' : 'none';
  this.lineThrough = this.lineThrough ? '' : 'line-through';
}      

在delete函數裡,使用EventEmitter發送一個事件。deleteRequest這個property需要加上@Output的注解。

在parent Component裡,監聽從child Component發送過來的自定義事件:

<app-item-detail (deleteRequest)="deleteItem($event)" [item]="currentItem"></app-item-detail>      

繼續閱讀