I'm trying to update a property in an object inside an array using an EventEmitter in a child component.
interface productItem {
keepOpen: boolean;
}
products$:productItem[] = Array(7).fill(
{
keepOpen:false
}
)
I'm using this function when the user clicks on the button :
shouldKeepAddToBagOpen(dataFromChild: boolean, index: number): void {
// handle callback
this.keepAddToBagOpen = dataFromChild;
this.products$[index].keepOpen = dataFromChild;
}
However it is affecting all the items in the array, not only the one with the given index
:
What am I doing wrong?
CodePudding user response:
When Array.fill gets passed an object, it will copy the reference and fill the array with references to that object.
You could instead use something like:
products = Array.from({length:7},()=> ({'keepOpen':false}))