I am working with Angular 2 with TypeScript. I have User Management component where I have table of whole users.
When any user in table is clicked then forms appeaer with his whole properties to edit. Choosing user occurs event as below:
onUserSelected(event) { var selectedId = event.data.id; this.selectedUser = this.users.filter(user => user.id === selectedId)[0] }
The problem is when selectedUser is being edited his properties also changes in table and it doesnt look so good. I tried to create copy myself as below but it didn't help - user class
clone() { var cloned = new User(this.id, this.login, this.name, this.surname, this.phone); return cloned; }
Maybe I am doing something which is not good practice in Angular2?
The Object. assign() function can be used to copy all enumerable own properties from one or more source objects to a target object. This function returns the target object to the newObject variable. Here's an example of copying by assigning in TypeScript.
To create a deep copy of an array in TypeScript, install and use the lodash. clonedeep package. The cloneDeep method recursively clones a value and returns the result. The cloneDeep method returns an array of the correct type.
Similar to adding elements to arrays without mutating them, You can use the spread operator to copy the existing object into a new one, with an additional value. If a value already exists at the specified key, it will be overwritten.
Try using
this.user = Object.assign({}, currentObject);
As mentioned by @AngularFrance, this will only work for shallow-copying objects, seek another implementation if there's a need to deep-copy an object.
You can use lodash :
https://lodash.com/docs#cloneDeep
lodash is recommended for lot of objects / array manipulations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With