Angular 2:Parent-Child 组件 属性 绑定

Angular 2: Parent-Child Component Property Binding

如何 属性 绑定 child 组件?我想通过它的 parent 组件使我的变量 high 变为 false or !this.high 但问题是,child 正在循环

app-product

<button class="ui primary small button"(click)="clearVals()">Clear Selected</button>
<app-product-list [dataSource]="data"></app-product-list>


@ViewChild(ProductListComponent) prodList: ProductListComponent;
clearVals() {
    this.selectedOutsourced = this.selectedPrice = 0;
    this.prodList.clear();
    this.selectedArray = [];
}

app-product-列表

<div class="products-cards" *ngFor="let product of dataSource['docs']">
      <app-product-card [product]="product"(highlightEvent)="highlight($event)">
      </app-product-card>
</div>


@ViewChild(ProductCardComponent) prodCard: ProductCardComponent;

app-product-卡

<div class="list card ui" (click)="highlight()" [class.selected]="high"> </div>


high : boolean = false;
highlight(){
     this.high = !this.high;
}

也就是parenting的顺序。最上面的是 parent 到它的 child

这个很有趣,我读了 5 次后才注意到。

你的 div 有一个 *ngFor。 你的 child 在那个 div 里,所以 child 会被循环掉。

<div class="products-cards" *ngFor="let product of dataSource['docs']">
          <app-product-card [product]="product"(highlightEvent)="highlight($event)">
          </app-product-card>
    </div>

应该是

    <div class="products-cards" *ngFor="let product of dataSource['docs']">
        </div>
<app-product-card [product]="product"(highlightEvent)="highlight($event)">
              </app-product-card>

然后在你的 child

@Input()
  set product(product: any) {
    highlightF(product);
  }

highlightf(product: any){
  this.hightlight.emit(product);
}

现在在您的 parent 中:

//Do something to set product.highlight

您需要将子组件中的代码更改为

app-product-card 子组件 typescript

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Input() product: any;

@Output() highlightEvent= new EventEmitter();

highlight(){
   this.highlightEvent.emit(somevalue);

}