Angular 2: Parent-Child Component Property Binding

4.6k views Asked by At

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

2

There are 2 answers

0
Swoox On BEST ANSWER

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
0
Sunil Kumar On

you need to change the code in child component as

app-product-card child component typescript

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

@Input() product: any;

@Output() highlightEvent= new EventEmitter();

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

}