且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular应用里child Component如何向parent Component发送事件

更新时间:2022-09-09 16:34:44

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>