Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Array.push not working properly

When i push the item into the array, item is pushed but problem is that all items in array becomes same as the last item pushed.

pushspecification() {
        this.specificationSaveDetailList.push(this.specificationsaveDetail);
    }

Here is the plunker code: plunker_Code
In this plunker example i select item from the dropdown and provide the description and click add button and table is populated with array item.

like image 762
Amir Avatar asked Mar 10 '23 02:03

Amir


1 Answers

Because you are binding pushing same object with its reference to an array element. So when you are updating specificationsaveDetail object reference it updates the all elements of array as they are references of same element.

To make it work, you have to create a new object copy and push it inside array. For then same you could use Object.assign

pushspecification() {
    this.specificationSaveDetailList.push(Object.assign({}, this.specificationsaveDetail));
}

Demo Plunker

like image 193
Pankaj Parkar Avatar answered Mar 19 '23 00:03

Pankaj Parkar