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)
CodePudding user response:
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).
CodePudding user response:
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);
}