'angular 2 (click) passing iteration variable and [class.selected] passing function
The following is taken from 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;
}
Two questions,
Q1. where it says
(click)='clicked(myProduct)'
is the argument for clicked the same as the product property on ProductRow component? I am used to passing $event to clicked. Why pass "myProduct" instead?
Q2. where it says
[class.selected]="isSelected(myProduct)"
it seems like we are doing
[class.selected]="false"
for all products cuz none of them is selected initially. How is angular able to call isSelected(myProduct) again and again? How does angular decide when to call isSelected?
Solution 1:[1]
this is an example of parent-child
communication in angular2.
when you are using (click)='clicked(myProduct)'
event, what essentially you are doing is emitting
the value of the selected product using @ouput onProductSelected
property as shown here :
this.onProductSelected.emit(product);
$event` here would be equivalent to `#myProduct.value
when any event gets executed, angular2's change detections kicks-in; checking all the template expression values. It then updates the property binding as per value changes. now everytime value of myProduct
changes, the property binding [class.selected]
need to get updated , hence isSelected
method gets called.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | crthompson |