创建一个提醒功能
创建一个提醒功能,接收一个商品作为输入,检查商品价格,如果大于700则显示 “Notify Me” 按钮。
1、创建一个商品提醒组件
右键单击‘product-list’ 文件夹,使用Angular Generator生成一个名为product-alerts的新组件。操作如下图:(官网是在app下创建,这样的话无法实现此功能。)
生成了三个文件:
product-alerts.component.ts
product-alerts.component.html
product-alerts.component.css
2、打开新创建的 ‘product-alerts.component.ts’
@Component 装饰器。这表明它下面的类是一个组件。它提供了有关该组件的元数据,包括它的模板(html)、样式(css/less)和选择器( 用于标识该组件。该选择器是当 Angular 组件在页面中渲染出 HTML 元素时使用的名字。)。
3、设置商品提醒组件,让它接收一个商品作为输入
1、从@angular/core 导入 Input。
‘product-alerts.component.ts’ 中
import { Input } from '@angular/core';
2、在 ProductAlertsComponent 类的定义中,定义一个带 @Input 装饰器的 product 属性。@Input 装饰器指出其属性值是从组件的父组件(在本例中就是商品列表组件)中传入的。(所以product-alert组件要建在product-list下而不是app下)
‘product-alerts.ts’中
export class ProductAlertsComponent implements OnInit {
@Input() product;
constructor() { }
ngOnInit() {
}
}
4、定义商品提醒组件的视图
在 product-alerts.component.html 模版,把作为占位符的 p 替换为如果商品价格超过 700 美元就要显示出来的“Notify Me”按钮。
‘product-alerts.conponent.html’ 中
<p *ngIf="product.price > 700">
<button>Notify Me</button>
</p>
5、将商品提醒组件显示在商品列表组件中
在 ‘product.component.html’ 中加上
<button (click)="share()">
Share
</button>
<app-product-alerts
[product]="product">
</app-product-alerts>
商品提醒组件会从商品列表中获取商品作为输入信息。通过该输入,它会根据商品的价格显示或隐藏 “Notify Me” 按钮。由于 Phone XL 的售价超过了 700 美元,所以该商品上会出现“Notify Me”按钮。
运行结果如下: