What is the process for creating a Deep Copy of an object in Angular?

I have a specific entity class defined as follows:

export class Contact {
  id: number;
  firstName: string;
  lastName: string;

  constructor(id?, firstName?, lastName?) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
  }
 
}

I am now looking to create a separate instance from the Contact class:

export class MyComponent {
  
  contactSrc = new Contact();
  contactDest = new Contact();
  
  constructor() {
      this.contactSrc.firstName = "Adam"
  }



  handleCopyOfObject() {
    console.log("firstName for contactSrc: " + this.contactSrc.firstName);

    this.contactDest = this.contactSrc;
    this.contactDest.firstName = "Mohsen";

    console.log("-----------result after copy -----------");
    console.log("firstName for contactSrc: " + this.contactSrc.firstName);
    console.log("firstName for contactDest: " + this.contactDest.firstName);
  }

}

When running the code, the output is as follows:

firstName for contactSrc: Adam
-----------result after copy -----------
firstName for contactSrc: Mohsen
firstName for contactDest: Mohsen

The issue is that modifying contactDest.firstName also impacts contactSrc.firstName. How can I update contactDest.firstName without affecting contactSrc.firstName?

Answer №1

To achieve the desired outcome, one can utilize either the spread operator or Object.assign().

userDetails = {
    name: 'Alice'
}
updatedDetails = {...userDetails, name: 'Smith'};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When exporting data to Excel, the date is automatically adjusting based on the timezone. Is there a way to prevent this from happening

Whenever I attempt to export data to excel in angular, I encounter an issue with time zones. The date in the database is set in timezone 'x', while I am exporting data from timezone 'y'. As a result, the exported data in Excel displays ...

Connecting HTML to an AngularFirestore collection using snapshotChanges

In my mobile app, I am using AngularFirestore2v5/rxjs to connect a hybrid Ionicv3/Angularv4 app to a Firestore collection. While binding UI with AngularFirestore.valueChanges works fine, switching to snapshotChanges for retrieving the id is causing some is ...

Is it acceptable to have an empty dependency array in React.useEffect?

Within my child React component, I receive an itemList prop from the parent component. This prop is an array of objects that contain data fetched from an endpoint. My goal in the child component is to enhance each object in the itemList array by adding mo ...

Comparing AngularJS controller and template encapsulation to Angular components: a breakdown

I've set up a state in my angularjs app called homeInside, complete with its own controller and template. Within that layout, I have various elements including a button with an ng-click event tied to the function doSomething. Additionally, there is an ...

Comparing Angular global variables: when to use static readonly in service class versus const

Which method is the better choice? @Injectable({ providedIn: 'root' }) export class MyService { static readonly VALIDITIES = new Map<number, string>([ ... ]); ... } OR: const Validities = new Map<number, string>([ .. ...

Having trouble importing PouchDB into an Angular 5.2.0 project

Struggling with integrating PouchDB into my Angular project, I've experimented with various import methods : import PouchDB from 'pouchdb'; import * as PouchDB from 'pouchdb'; In my service, I'm utilizing it like this : dat ...

Encountering an issue while compiling with TypeScript, where a typescript class that involves Meteor and Mongo is throwing an error stating "Property 'Collection' does not exist on type 'typeof Mongo'."

During the compilation of Meteor, an error in the console states "Property 'Collection' does not exist on type 'typeof Mongo'." I'm curious if anyone has encountered this issue before and how they resolved it. I am working with me ...

What is the method for including as: :json in your code?

I have a file with the extension .ts, which is part of a Ruby on Rails application. The code in this file looks something like this: export const create = async (params: CreateRequest): Promise<XYZ> => { const response = await request<XYZ> ...

How can the panel within an accordion be enlarged or minimized?

Currently, I am implementing an accordion feature with the option to expand or collapse all panels using two buttons. My goal is to allow users to manage each panel within the accordion individually. However, I have encountered an issue that needs attenti ...

Is there a way to package extra files along with `NodejsFunction` in Node.js?

I am looking to add another HTML file to the source code, like shown below. https://i.sstatic.net/OyxDM.png Here is my current code: const mailerFunction = new aws_lambda_nodejs.NodejsFunction(this, 'ApiNotificationHandler', { runtime: lambd ...

retrieve a stream of data from a subscription

After conducting various experiments, I decided to share the code in its original form to determine the best practice: Within a function (in the service), I subscribe to a result as a BLOB and save it as content of a file on the local file system using Fil ...

The error occurs when trying to access the `pipe` property of an undefined variable in NgbTypeahead

I am currently working on implementing the typeahead directive of ng-bootstrap. Below is the code snippet from my HTML file: <input type="text" class="form-control" formControlName="payee" autofocus [ngbTypeahead]="searchPayee"> Here's the cor ...

A guide to identifying a user's browser type using server-side code (Node.js) when making an API request

Can someone help me differentiate between REST API calls made from a desktop browser and those from a mobile browser, specifically tablets? I am currently using Node Express on my server side. ...

What is the process for converting language json files into different languages?

I'm currently using ngx-translate to localize an Angular app. With over 20 languages that need translation, I am in search of a tool that can efficiently translate the language json files. While I did come across a helpful website, it proved to be ti ...

What steps should I take to resolve the 'invalid mime type' issue while transmitting an image as a binary string to Stability AI via Express?

Currently, I am facing an issue while attempting to utilize the image-to-image API provided by stabilityAI. The task at hand involves sending an image as a binary string through my express server to the stability AI API. However, when I make the POST reque ...

The formBuilder controls' setValue() and patchValue() methods are not functional when called within a method of a Cordova plugin

In developing my Ionic tabs app, I have integrated the cordova-plugin-datepicker and utilized Angular Material to design the form fields. One issue I encountered is setting the text input's value with the date obtained from the plugin’s calendar in ...

Reduce the size of the JSON file located in the Assets folder during an Angular build

What is the most effective method to compress JSON files in an Angular production build? I currently have a JSON file in the assets folder that remains unchanged when the production build is completed. During development, the file appears as the Developme ...

"What could be the reason behind the injected service not being successfully passed from the parent component to the child component when navigating using route.navigate in Angular

I currently have a parent component and a child component set up in my project. (parent component) @Component({ selector: 'app-parent', providers: [SimpleService] }) (child component) @Component({ selector: 'app-child' }) Everyt ...

How can I display milliseconds from a date in Angular2+?

I recently encountered an issue while working with a custom pipe that was used to display time. I attempted to modify it so that it could also show milliseconds: {{log.LogDate|jsonDate|date:'dd.MM.yyyy &nbsp; HH:mm:ss.sss'}} Here is the cod ...

What are the steps to integrate TypeScript into JavaScript code?

How can I import a TypeScript class in a Node CommonJS JavaScript file? When using mongoose in my TypeScript code, I typically do the following: // user.model.ts export const UserModel = model<User>('User', schema); In my JavaScript code: ...