Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy values of objects without binding them

Tags:

angular

I'd like to copy copy the values of an object (item) to another one (editedItem) to put it into a form and modify it while the original object still is displayed unchanged.

<a (click)="editedItem=item">Edit</a>

With this approach the two objects are bound, Item changes when the editedItem is modified. Is there a way to just copy the values without binding the objects?

like image 584
Seltsam Avatar asked Jul 19 '16 11:07

Seltsam


2 Answers

You can use JSON.parse(JSON.stringify()) if you don't care about the types.

Here is an example:

HTML

<a (click)="copy()">Edit</a>

TS

copy() {
   this.editedItem = JSON.parse(JSON.stringify(this.item))
}
like image 107
Filip Lauc Avatar answered Oct 08 '22 18:10

Filip Lauc


Well, would liked to have done this without an extra function, but this works.

  <a (click)="toEditItem(item)">Edit</a>

  toEditItem(item) {
      this.editItem= Object.create(item);
  }
like image 24
Seltsam Avatar answered Oct 08 '22 18:10

Seltsam