Angular2, data is kept bound to original variable inside function
I am calling a function to replicate data inside a * ngFor loop as shown below.
<li (click)="replicateTicket(data);"> Replicate</li>
Inside the function, I update the name and id of the variable and push it inside the array. (In this example, I am not nudging the data to explain the behavior more vividly.
replicateTicket(data:any){
data.name = data.name + ' (Replicated)';
console.log(this.ticketList[this.ticketList.length-1].id);
data.id = 0;
console.log(this.ticketList[this.ticketList.length-1].id);
}
What I want is if the source data id is 5, then it shouldn't change to 0.
-
Start plunker
-
click on 458 abc.
-
It should only update new data, not current data.
Am I doing something wrong?
+3
source to share
2 answers
You need to create a copy of the current object, modify it and then insert the new object into the array, something like this, for example: (I used the code from your Plunker)
replicateTicket(ticket:any){
let t = JSON.parse(JSON.stringify(ticket));
t.name += ' (Replicated)';
t.id = 0;
this.ticketList.push(t);
}
+5
source to share