在本节中,将设置商品提醒组件,当用户点击‘Notify Me’的时候,像商品列表组件发出事件。
1、打开 product-alerts.component.ts, 从 @angular/core 中导入 Output 和 EventEmitter。
2、在组件类中,用 @Output 装饰器和一个事件发射器(EventEmitter)实例定义一个名为 notify 的属性。这可以让商品提醒组件在 notify 属性发生变化时发出事件。
在 ‘product-alerts.component.ts’ 中
export class ProductAlertsComponent {
@Input() product;
@Output() notify = new EventEmitter();
}
3、在‘product-alerts.component.html’ 中,用事件绑定更新 ‘Notify Me’ 按钮,以调用notify.emit() 方法。
在‘product-alerts.component.html’中
<p *ngIf="product.price > 700">
<button (click)="notify.emit()">Notify Me</button>
</p>
5、点击改按钮时,应该由父组件(商品列表组件)采取行动,所以,在product-list.component.ts 文件中,定义一个 onNotify() 方法。如下:
在‘product-list.component.ts’ 中
export class ProductListComponent {
products = products;
share() {
window.alert('The product has been shared!');
}
onNotify() {
window.alert('You will be notified when the product goes on sale');
}
}
6、最后,修改商品列表组件来接收商品提醒组件的输出。在 product-list.component.html 中,把 app-product-alerts 组件(就是它显示的“Notify Me”按钮)的 notify 事件绑定到商品列表组件的 onNotify() 方法。
在 ‘product-list.component.html’ 中
<button (click)="share()">
Share
</button>
<app-product-alerts
[product]="product"
(notify)="onNotify()">
</app-product-alerts>
点击‘Notify Me’ 后显示如下: