简体   繁体   English

Angular2,Data也保持绑定到函数内部的原始变量

[英]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);">&nbsp; 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。

  1. Run plunker 运行plunker

  2. click on 458 abc. 点击458 abc。

  3. 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.

相关问题 修改实例变量也是修改原始数组 - Modifying an instance variable is also modifying the original array JavaScript 将原始数组保留在递归中 function - JavaScript keep the original array in recursive function Angular2不能在模板以外的任何地方访问变量 - Angular2 cant acces variable anywhere but in template 使用异步调用angular2分配变量 - assigning variable using async call angular2 如何将数据推送到angular2中的模型数组 - how to push data to array of a model in angular2 地图函数内部的charCodeAt()返回原始数组 - charCodeAt() inside map function returning original array 更新使用Object.assign创建的变量中的数组也将更新原始变量 - Updating an array within a variable created using Object.assign is also updating the original variable ruby将数组分配给另一个变量,并且从该分配变量中删除元素时,也会在原始数组上删除它 - ruby assign array to another variable and when delete element from that assign variable deleted on original array also 表单是在ng-repeat内数据绑定到ng模型的,但是所有重复的值都被更改了吗? - Form is data-binded to a ng-model inside ng-repeat… but all repeated values are changed? Angular2教程:本节中的ID变量如何自动递增? - Angular2 Tutorial: How is the ID variable in this section being auto incremented?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM