以下摘自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组件上的product属性相同吗?我习惯于将$ event传递给click。为什么要通过“myProduct”呢?

Q2。它在哪里说
[class.selected]="isSelected(myProduct)"

好像我们在做
[class.selected]="false"

对于所有产品,因为最初没有选择任何产品。
Angular 如何一次又一次调用isSelected(myProduct)? Angular 如何确定何时调用isSelected?

最佳答案

这是angular2中parent-child通信的示例。

当您使用(click)='clicked(myProduct)'事件时,实际上您在做的就是使用emitting属性@ouput onProductSelected所选产品的值,如下所示:

this.onProductSelected.emit(product);
$event` here would be equivalent to `#myProduct.value

当执行任何事件时,angular2的更改检测就会启动;检查所有模板表达式值。然后,它会根据值更改来更新属性绑定(bind)。现在每次myProduct的值更改时,需要更新绑定(bind)[class.selected]的属性,因此会调用isSelected方法。

10-06 11:51