[英]Angular2, Data is keep binded to the original variable inside the function also
I'm calling a function to replicate the data inside *ngFor loop like below. 我正在调用一个函数来复制* ngFor循环中的数据,如下所示。
<li (click)="replicateTicket(data);"> Replicate</li>
Inside the function I'm updating name and Id of variable and pushing it inside the array. 在函数内部,我正在更新变量的名称和ID,并将其推送到数组中。 (In given example I'm not pushing 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 id of original data is 5 than it should not change to 0. 我想要的是如果原始数据的id是5而不是它不应该变为0。
click on 458 abc. 点击458 abc。
It should only update the new data and not the current one. 它应该只更新新数据而不是当前数据。
Am I doing Something wrong? 难道我做错了什么?
You need to create copy of the current object, change it and then push new object into an array, something like this for example: (I used code from your Plunker) 您需要创建当前对象的副本,更改它然后将新对象推送到数组中,例如:(我使用了Plunker中的代码)
replicateTicket(ticket:any){
let t = JSON.parse(JSON.stringify(ticket));
t.name += ' (Replicated)';
t.id = 0;
this.ticketList.push(t);
}
you also can do this 你也可以这样做
replicateTicket(ticket:any){
let a = Object.assign({}, ticket);
a.name = ticket.name + ' (Replicated)';
a.id = 0;
this.ticketList.push(a);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.