Search code examples
angularbooleanparent-childangular-componentsproperty-binding

Angular 2: Parent-Child Component Property Binding


How do you property bind a child component? I want to make my variable high to false or !this.high through its parent component but the thing is, the child is being looped

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-list

<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-card

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


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

That is the order of the parenting. The topmost is the parent down to its child


Solution

  • This one is funny I just noticed after reading this like 5 thimes.

    Your div has a *ngFor. Your child is in that div, So the child will be looped ofc.

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

    Should be

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

    Then in your child

    @Input()
      set product(product: any) {
        highlightF(product);
      }
    
    highlightf(product: any){
      this.hightlight.emit(product);
    }
    

    Now in your parent:

    //Do something to set product.highlight