4

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.

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

@Amir Glad to know that, Thanks :)
today you can use pushspecification() { this.specificationSaveDetailList.push({...this.specificationsaveDetail}); }
0

You can use like this :

Array.push(Object.assign({}, this.utility));

Comments

0

Use the below approach for when you are adding the elements into array.

const element: IEmployee[] = []; //initialize the array
element.push(employee);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.