Angular父子Component之间的事件通知机制

时间:2022-07-23
本文章向大家介绍Angular父子Component之间的事件通知机制,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

例子:product-list为parent Component,product-alert为child Component.

(1) child Component里必需的开发

从@angular/core里导入Input, Output和EventEmitter:

新建一个名为product的属性,用于从parent Component里接收当前选中的product.

新建一个EventEmitter实例,用于向parent Component发送事件。

在product alert模板里,给按钮点击click事件附上处理函数:notify.emit()

<p *ngIf="product.price > 700">
  <button (click)="notify.emit()">Notify Me</button>
</p>

(2) parent Component里必需的开发

使用语法中括号[]给child Component的Input属性赋值,使用语法大括号{}给child Component的Output属性赋值:

onNotify的实现,位于parent Component ts文件内:

最后的效果: