Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

<li (click)="replicateTicket(data);">&nbsp; Replicate</li>

Inside the function I'm updating name and Id of variable and pushing it inside the array. (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.

  1. Run plunker

  2. click on 458 abc.

  3. It should only update the new data and not the current one.

Am I doing Something wrong?

like image 538
YASH DAVE Avatar asked Feb 14 '26 06:02

YASH DAVE


1 Answers

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)

replicateTicket(ticket:any){
    let t = JSON.parse(JSON.stringify(ticket));
    t.name += ' (Replicated)';
    t.id = 0;
    this.ticketList.push(t);
}
like image 63
Stefan Svrkota Avatar answered Feb 16 '26 20:02

Stefan Svrkota



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!