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

79 阅读1分钟

例子: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文件内:

最后的效果:

要获取更多Jerry的原创文章,请关注公众号"汪子熙":