Replicating entities in TypeScript

I am currently developing an Angular 2 application using TypeScript. In a User Management component, I have implemented a table that displays all the users in my system.

When a user is clicked on within the table, a form appears with their complete set of properties for editing. The selection of a user triggers the following event:

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

However, I encountered an issue where when the selectedUser is edited, the changes reflect directly in the table as well, which is not ideal from a user experience standpoint. My attempt to create a copy of the user by implementing a clone function did not resolve the issue - see code below:

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

It seems like there might be a better way to handle this situation in Angular 2. Any suggestions or recommendations would be greatly appreciated.

Answer №1

Consider utilizing

this.newUser = Object.assign({}, existingObject);

As pointed out by @JSExperts, keep in mind that this method is suitable for copying shallow objects only; for deep object copying, explore alternative solutions.

Answer №2

For working with objects and arrays, consider utilizing lodash:

https://lodash.com/docs#cloneDeep

Lodash is highly recommended for a wide range of object and array manipulations.

Answer №3

One approach is to bind the editor form to a new User object named editUser, instead of directly using the selectedUser variable that points to an element in your user collection. When the onUserSelected(event) function is triggered, you can set the editUser by copying over the mutable properties from the selected user object. Upon submitting the edit form with (ngSubmit)="editSubmit()", you can update the original selected user object with the edited properties.

This could look something like this:

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.cloneAttributes(this.selectedUser);
}

editSubmit(event) {
    this.selectedUser = this.cloneAttributes(this.editUser);
}

cloneAttributes(obj: any) {
    return Object.assign({}, obj);
}

Keep in mind that the current implementation of simpleClone() may not work for deep cloning scenarios where User objects contain references to other objects. If needed, consider creating a proper deep cloning function for more complex data structures.

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

Utilizing files that do not have the extension '.ts' or '.tsx' within the 'ts_library' as dependencies

My current challenge involves importing a JSON file from TypeScript while utilizing the resolveJsonModule flag in my tsconfig. The problem lies in how I can provide this JSON file to ts_library since it seems unable to locate the file. This issue extends t ...

Having trouble reloading a seekbar (input range) in Angular 7 with a function?

I am currently in the process of developing a music player using Angular 7, and below is the HTML code for my component: <div class="track-controller"> <small>{{musicPlayerService.getCurrentTime()}}</small> <div class="progress- ...

"Troubleshooting Primeng's p-table filter issue when using an editable FormArray - encountering problems with the

I'm encountering a problem with the filter functionality on primeng p-table when using formarray controls. The filter doesn't seem to work correctly, so I tried registering a custom filter and testing it. However, I found that the value is null f ...

What are the steps for integrating and expanding a JavaScript library using rollup, TypeScript, and Angular 2?

I am currently working on a project called angular2-google-maps-test and I am interested in integrating and expanding upon the JS library found at js-marker-clusterer npm install --save js-marker-clusterer It seems that this library is not structured as ...

Tips for adding a time increment of 24 hours to a date variable in Angular 6

My goal is to update a date variable called EndDate stored in localStorage by adding exactly 24 hours to it. The current value in the localStorage is Sun Jun 09 2019 20:39:44 GMT+0530 (India Standard Time). var endDate = new Date(); endDate.setDat ...

While trying to update Angular 5 to 6, I am encountering an incompatible peer dependency error when utilizing the ng update @angular/core command

I have been encountering issues while trying to upgrade my Angular app from version 5 to version 6 by following this guide. After successfully running the commands below: npm install -g @angular/cli npm install @angular/cli ng update @angular/cli An err ...

ERROR : The value was modified after it had already been checked for changes

Encountering an issue with [height] on the main component and seeking a solution Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '753'. Current value: '731'. I have th ...

proper method for adding line breaks in json

I am experiencing difficulty in creating a line break using \r\n with the given payload on this particular screen. I am on a quest to determine the correct json payload that needs to be dispatched to the frontend in order for it to register as a ...

When using @Viewchild, it can sometimes lead to encountering

Within my project, I have a component called SideToggleComponent that contains a function: activeButton(value){ ... } I am trying to call this function from another component called BlogComponent. To do so, I am using @ViewChild as shown below: @ ...

I aim to toggle the visibility of input fields upon clicking a button

Form.html <form [formGroup]="myForm"> <ion-button [(ngModel)]="isActive"(click)="onClick()" >Add</ion-button> <ion-item> <ion-label position="floating">First Name</ion-label&g ...

In TypeScript, both 'module' and 'define' are nowhere to be found

When I transpile my TypeScript using "-m umd" for a project that includes server, client, and shared code, I encounter an issue where the client-side code does not work in the browser. Strangely, no errors are displayed in the browser console, and breakpoi ...

Having trouble with Angular NgbModal beforeDismiss feature?

My goal is to add a class to the pop up modal before closing it, and then have it wait for a brief period before actually closing. I've been trying to do this using the beforeDismiss feature in the NgbModalOptions options in Angular Bootstrap's d ...

Customizing the Switch component individually for each item fetched from an API in React Native

I'm struggling with setting the switch button individually for each item in my API. Despite trying multiple solutions, none of them seem to work for me. const results = [ { Id: "IySO9wUrt8", Name: & ...

Using Typescript to remove an element from an array inside another array

I've encountered an issue while trying to remove a specific item from a nested array of items within another array. Below is the code snippet: removeFromOldFeatureGroup() { for( let i= this.featureGroups.length-1; i>=0; i--) { if( this.featureGr ...

After importing this variable into index.ts, how is it possible for it to possess a function named `listen`?

Running a Github repository that I stumbled upon. Regarding the line import server from './server' - how does this API recognize that the server object has a method called listen? When examining the server.ts file in the same directory, there is ...

"What could be causing my React Native app to build without any issues even though the TypeScript compiler is throwing

Recently, I decided to explore TypeScript in combination with Expo. I took the time to set up linter and formatter integrations like typescript-eslint to help me catch errors while coding. Periodically, I run npx tsc to ensure my code compiles correctly an ...

Obtain item from DataSource in Angular's MatTable

In my transaction-history.component.ts file, I have implemented a material data table that fetches data from a query to display it. Here is the code snippet: import { Component, OnInit } from '@angular/core'; import { Transaction } from '.. ...

Encountering an undisclosed CORS error on all requests from Angular frontend to NodeJS Express Server during preflight 200

After thorough testing with Postman, my backend server is functioning properly and generating the desired responses for all requests. However, my Angular app is encountering an unknown CORS error on every request despite receiving a 200 Preflight response ...

Since transitioning my project from Angular 7.2 to Angular 8, I noticed a significant threefold increase in compile time. How can I go about resolving this issue

After upgrading my project to Angular 8, I noticed a significant increase in compile time without encountering any errors during the upgrade process. Is there a way to restore the previous compile time efficiency? **Update: A bug has been identified as th ...

Challenges with Css Specificity

I'm having trouble adding a specific class to certain div elements. Here is the div in question: <div class="form-control drop-down-select"> </div> This is the CSS I have applied: .form-control.drop-down-select{ max-width: ...