简体   繁体   中英

Data not passing to child component from parent component in Angular

I have few checkboxes and I'm pushing those checkboxes values in to an array. Then I'm trying to access those data from child component using @Input decorator. But data is not even passing to the child component(Not displaying console.log). Could you please help me to fix this issue?

Parent Component (.ts)

public layers: any[] = [];

layerChange(e:any){
    var isChecked = e.target.checked;
    var id = e.target.attributes.id.nodeValue;
    const index = this.layers.findIndex(el => el.id === id);

    const layer = {
      isChecked: isChecked,
      id: id,
    }
    
    if(index > -1){
      this.layers[index].isChecked = isChecked;
    }else{
      this.layers.push(layer);
    }
    console.log(this.layers);
  }

.html

<input id="population" (change)="layerChange($event)" type="checkbox">
<input id="age" (change)="layerChange($event)" type="checkbox">
            

<app-esri-map [layerChange] = "layers"></app-esri-map>

Child Component (.ts)

 @Input() layerChange: Array<any>;
  console.log(layerChange)

Arrays are passed to children by reference.

You're only pushing new items to your layers array, so the reference keeps the same. Thus, Angular's change detection cycle won't be triggered and the OnChanges lifecycle hook won't detect any changes on that @Input .

You need to create a new instance each time you change your array. Or just use a shared service between those components. That way the parent will push items to the array and the child will listen to those changes (using Observables).

Do this instead

public layers: any[] = [];

layerChange(e:any){
    var isChecked = e.target.checked;
    var id = e.target.attributes.id.nodeValue;
    const index = this.layers.findIndex(el => el.id === id);

    const layer = {
      isChecked: isChecked,
      id: id,
    }
    
    if(index > -1){
      this.layers[index].isChecked = isChecked;
    }else{
      this.layers.push(layer);
    }
    this.layers = [...this.layers];
    console.log(this.layers);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM