Angular官网学习4:Angular入门,你的第一个应用(4)输出

在本节中,将设置商品提醒组件,当用户点击‘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’ 后显示如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值