以下内容摘自ng-book 2
@Component({
selector: 'products-list',
directives: [ProductRow],
inputs: ['productList'],
outputs: ['onProductSelected'],
template: `
<div class="ui items">
<product-row
*ngFor="let myProduct of productList"
[product]="myProduct"
(click)='clicked(myProduct)'
[class.selected]="isSelected(myProduct)">
</product-row>
</div>
`
})
class ProductsList {
/**
* @input productList - the Product[] passed to us
*/
productList: Product[];
/**
* @ouput onProductSelected - outputs the current
* Product whenever a new Product is selected
*/
onProductSelected: EventEmitter<Product>;
/**
* @property currentProduct - local state containing
* the currently selected `Product`
*/
currentProduct: Product;
constructor() {
this.onProductSelected = new EventEmitter();
}
clicked(product: Product): void {
this.currentProduct = product;
this.onProductSelected.emit(product);
}
isSelected(product: Product): boolean {
if (!product || !this.currentProduct) {
return false;
}
return product.sku === this.currentProduct.sku;
}
}
@Component({
selector: 'product-row',
inputs: ['product'],
... not relevant to the question
`
})
class ProductRow {
product: Product;
}
Run Code Online (Sandbox Code Playgroud)
两个问题,
Q1.在哪里说
(click)='clicked(myProduct)'
Run Code Online (Sandbox Code Playgroud)
是否与ProductRow组件上的产品属性相同的参数?我习惯将$ event传递给clicked.为什么要传递"myProduct"呢?
Q2.在哪里说
[class.selected]="isSelected(myProduct)"
Run Code Online (Sandbox Code Playgroud)
好像我们正在做
[class.selected]="false"
Run Code Online (Sandbox Code Playgroud)
对于所有产品,因为最初没有选择它们.角度如何能够一次又一次地调用isSelected(myProduct)?角度如何决定何时调用isSelected?
parent-child这是Angular2 中的通信示例。
当您使用(click)='clicked(myProduct)'事件时,您本质上所做的是emitting使用属性来获取所选产品的值 @ouput onProductSelected,如下所示:
this.onProductSelected.emit(product);
$event` here would be equivalent to `#myProduct.value
Run Code Online (Sandbox Code Playgroud)
当任何事件被执行时,Angular2 的变化检测就会启动;检查所有模板表达式值。然后,它根据值的变化更新属性绑定。现在每次值发生myProduct变化时,属性绑定都[class.selected]需要更新,因此isSelected方法会被调用。
| 归档时间: |
|
| 查看次数: |
10139 次 |
| 最近记录: |