angular 2(click)传递迭代变量和[class.selected]传递函数
发布时间:2020-12-17 18:05:09 所属栏目:安全 来源:网络整理
导读:以下内容摘自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]="myPr
|
以下内容摘自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;
}
两个问题, Q1.在哪里说 (click)='clicked(myProduct)' 是否与ProductRow组件上的产品属性相同的参数?我习惯将$event传递给clicked.为什么要传递“myProduct”呢? Q2.在哪里说 [class.selected]="isSelected(myProduct)" 好像我们正在做 [class.selected]="false" 对于所有产品,因为最初没有选择它们. 解决方法
这是angular2中父子通信的一个例子.
当您使用(click)=’clicked(myProduct)’事件时,您正在做的是使用@ouput onProductSelected属性发出所选产品的值,如下所示: this.onProductSelected.emit(product); $event` here would be equivalent to `#myProduct.value 当任何事件被执行时,angular2的变化检测开始;检查所有模板表达式值.然后它根据值更改更新属性绑定.现在每次myProduct的值发生变化时,属性绑定[class.selected]需要更新,因此调用了isSelected方法. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
