Spread the love

In this tutorial we will learn to copy object without reference in angular. Objects and array are work on reference by address methodology means Objects and array keeps the address means if you change anything in the object or array from anywhere then it will change the value in original object.

Angular is most popular frontend framework and not only in angular even in javascript or other framework we ca land into the same problem so to copy object without reference in angular here is the simplest solution

Copy object / Array in angular

Simplest way to copy a object in angular or javascript is below

let obj=[{"title":"test"}];
let copiedObj = JSON.parse(JSON.stringify(obj));

Here, we copied using json stringify and json parse method, now if you change value in copiedObj it won’t change the values of obj variable

Another way to copy the object we can use Object.assign but it won’t work in case of nested objects

let obj=[{"title":"test"}];
let copy = Object.assign({}, obj)

So as you can we have used two methods here

  1. Object.assign : Used to copy but nested objects not work
  2. JSON.parse and JSON.strigify : Used to copy the object without reference in nested object

Let’s take an example of convert JSON string to JSON object in angular

Step 1 : Create an angular app

First step is to setup an angular app using below command

ng new example-app

Step 2: Create a Component

Create a component and add json stringify and parse in component

ng g c hello-world
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

  selector: 'app-hello-world',
  templateUrl: './hello-world.component.html',
  styleUrls: ['./hello-world.component.css'],
export class HelloWorldComponent implements OnInit {
  obj:Array<object> = [{"title":"test"},{"title":"test2"}];
  copy: Array<object>;
  copyWithoutRef: Array<object>;
  constructor() {
    this.copy = JSON.parse(JSON.stringify(this.obj));
    this.copy[0]['title']="Copied Title";


  ngOnInit() {}

Here we used to convet the string to object and object to string.

Step 3 : Create template and add html

Now, add simple html template with a *ngFor

<h2>Copy without reference</h2>

<div *ngFor="let val of copy">
  {{ val.title }}

<h2>Copy with reference</h2>

<div *ngFor="let val of copyWithoutRef">
  {{ val.title }}

Live Example and code:

Leave a Reply