angular 2 (click) passing iteration variable and [class.selected] passing function

Discussão em 'Angular' iniciado por abdullam, Dezembro 19, 2024.

  1. abdullam

    abdullam Guest

    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?

    Continue reading...

Compartilhe esta Página