What's alternative to angular.copy in Angular

How can I copy an object and lose its reference in Angular?

With AngularJS, I can use angular.copy(object), but I'm getting some error using that in Angular.

EXCEPTION: ReferenceError: angular is not defined


Assuming you are using ES6, you can use var copy = Object.assign({}, original). Works in modern browsers; if you need to support older browsers check out this polyfill

update:

With TypeScript 2.1+, ES6 shorthand object spread notation is available:

const copy = { ...original }

Till we have a better solution, you can use the following:

duplicateObject = <YourObjType> JSON.parse(JSON.stringify(originalObject));

EDIT: Clarification

Please note: The above solution was only meant to be a quick-fix one liner, provided at a time when Angular 2 was under active development. My hope was we might eventually get an equivalent of angular.copy(). Therefore I did not want to write or import a deep-cloning library.

This method also has issues with parsing date properties (it will become a string).

Please do not use this method in production apps. Use it only in your experimental projects - the ones you are doing for learning Angular 2.


The alternative for deep copying objects having nested objects inside is by using lodash's cloneDeep method.

For Angular, you can do it like this:

Install lodash with yarn add lodash or npm install lodash.

In your component, import cloneDeep and use it:

import { cloneDeep } from "lodash";
...
clonedObject = cloneDeep(originalObject);

It's only 18kb added to your build, well worth for the benefits.

I've also written an article here, if you need more insight on why using lodash's cloneDeep.


For shallow copying you could use Object.assign which is a ES6 feature

let x = { name: 'Marek', age: 20 };
let y = Object.assign({}, x);
x === y; //false

DO NOT use it for deep cloning


Use lodash as bertandg indicated. The reason angular no longer has this method, is because angular 1 was a stand-alone framework, and external libraries often ran into issues with the angular execution context. Angular 2 does not have that problem, so use whatever library that you want.

https://lodash.com/docs#cloneDeep