Cloning TypeScript Objects

I am working with Angular 2 with TypeScript. I have a user management component where I have a table for all users.

When you click any user in the table of the form, all its properties are processed for editing. When a user is selected, an event occurs, as shown below:

onUserSelected(event) { var selectedId = event.data.id; this.selectedUser = this.users.filter(user => user.id === selectedId)[0] } 

The problem is when selectedUser is edited, its properties also change in the table, and it doesn't look so good. I tried to create a copy myself, as shown below, but that did not help - user class

  clone() { var cloned = new User(this.id, this.login, this.name, this.surname, this.phone); return cloned; } 

Maybe I am doing what is not good practice in Angular2?

+6
source share
3 answers

Try using

 this.user = Object.assign({}, currentObject); 

As @AngularFrance has already been mentioned, this will only work for objects with shallow copying; look for another implementation if there is a need for deep copying of the object.

+14
source

You can use lodash:

https://lodash.com/docs#cloneDeep

lodash is recommended for many manipulations with objects / arrays.

+5
source

You can bind the editor form to an empty user object, say editUser , instead of the selectedUser variable (which points to an element of your user collection). In onUserSelected(event) you must initialize editUser by cloning the mutable properties of the selected user objects. After submitting the edit form ( (ngSubmit)="editSubmit()" ), you replace the original properties in the selected user object in the user collection.

Something along the lines of:

 editUser: User = new User(); selectedId: number; selectedUser: User; onUserSelected(event) { this.selectedId = event.data.id; this.selectedUser = this.users.filter(user => user.id === this.selectedId)[0]; this.editUser = this.simpleClone(this.selectedUser); } editSubmit(event) { this.selectedUser = this.simpleClone(this.editUser); } simpleClone(obj: any) { return Object.assign({}, obj); } 

The implementation of simpleClone is not suitable for deep cloning, so if your user objects contain links to other objects, this should be turned into the correct cloning function.

+4
source

Source: https://habr.com/ru/post/1014510/


All Articles