Tips on updating an object in Angular 2/4 without losing the reference

Here's my scenario: I have two instances, originalMember and toSaveMember, both belonging to the same class called Person. How can I update all the values from toSaveMember to originalMember, while still retaining the original reference of originalMember? To clarify, I want to achieve the following:

originalMember.name = toSaveMember.name;
originalMember.age = toSaveMember.age;

I am looking for a more automatic solution as opposed to manually updating each field. Do you have any suggestions?

Many thanks!

Answer №1

To transfer all properties from toSaveMember to originalMember while maintaining separate object references for both, you can employ the Object.assign method:

Object.assign(originalMember, toSaveMember);

In case your platform doesn't support ES6, there exists a polyfill for Object.assign that you can utilize with older versions.

Answer №2

Retain the old elements while incorporating some fresh additions.

function addNewMember(_name: string, _age: number) {
  existingMember.name = newMember.name;
  existingMember.age = newMember.age;
  // alternatively, you can use @Saravana's method
  existingMember = newMember;

Next, update the name and age to your desired values.

newMember.name = _name;
  newMember.age = _age;
}

Remember to declare both objects within the component scope (this.).

If you wish to create a list of original Members, utilize an array to store the values in positions like array[0] for the first member, array[1] for the second member, and so forth.

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

What is the best way to display "No results found" in Mat-select-autocomplete?

I am working with the mat-select-autocomplete for a multiselect dropdown. When searching for values that are not in the list, I want to display a message saying "No results found". Can someone please help me achieve this? Link to Code ...

I am currently struggling to set up test unit cases and am having difficulty mocking POST HttpClientRequests. It's a bit of a roadblock for me at the

As I delved into the process of mocking an HttpRequest for a certain project, I realized that I should start with a simpler project that I created from scratch. Currently, my focus is on mocking an HTTP POST Request using Angular for Test Cases. The proje ...

Is it possible to implement Angular Universal on Github Pages?

Is it doable to Deploy Angular Universal on Github Pages? I've come across some solutions such as angular-cli-ghpages, but from what I understand, these options don't pre-render content for SEO purposes. ...

The dynamic duo of MongoDB and Prisma: forging a groundbreaking one-to-many relationship

Is it possible to establish a one-way m-to-n relationship without requiring both collections to have each other's ids? I am attempting the following: model Country { id String @id @default(auto()) @map("_id") @db.ObjectId ...

Eliminate the usage of JSON.stringify in the Reducer function

I have a system where I store chat messages in a dictionary with the date as the key and a list of messages as the value. Whenever a new message is added, the following code snippet is executed. Is there a way to enhance the existing code to eliminate the ...

Please refrain from clearing the text field as it will delete the input value

I feel like I must be overlooking something really minor because I just can't seem to find it! I've been attempting to sanitize the text input by setting the state to ('') and while it clears the variable, the HTML input keeps displayi ...

Retrieving a distinct value from an Observable

I am currently attempting to extract the monthlyFee value from this specific response body. ...

Is it possible to leverage TypeScript type support in Electron by incorporating require statements within functions or conditions?

The Electron Performance documentation advises against loading and running code too soon. It suggests using the strategy of deferring the loading of sizable modules until they are actually needed, rather than placing all require() statements at the top of ...

What is the significance of the error message "Surprisingly in Angular Zone despite expectations"?

Ever since upgrading from Angular 2 RC4 to RC5, I've been encountering this error. Although it doesn't seem to impact the application's functionality, it keeps appearing in the console and may draw attention away from other errors. Does any ...

What advantages does asynchronous microservices communication offer when it comes to enhancing the user interface experience?

When working with my Angular UI, I make a call to an API gateway endpoint like this: this.http.post(`/order`).subscribe(order => addNewOrderToList(order)); Following best practices in microservices architecture, the /order handler should publish an ev ...

Creating an interactive form in Angular2 using *ngFor, implementing two-way data binding with [(ngModel)], and including form validation

Challenge Description I'm currently working on developing a dynamic form that can update parts of the interface based on changes in the underlying model: When a user clicks a button, a new entity is added to the internal list of components and a ne ...

How can one correctly log out of an Angular application that is integrated with Firebase Authentication and Firestore?

How can I efficiently sign out of an Angular application that uses Firebase Authentication and Firestore? Although I can successfully sign in with Google authentication, signing out poses some challenges. My ultimate goal is to ensure that when a user cli ...

What is the process for assigning a custom React component as the Type for a prop in another component?

Currently, I am working on a customized GenericModal component and would like to include an array of my ModalText components as props in the GenericModal for display purposes. I want to specifically define the type of prop being passed, rather than using s ...

Prevent toggle button from activating panel expansion

Is there a way to add toggle buttons to the description section of an expansion panel without triggering the expansion panel when interacting with the buttons? I have included an example here. ...

Is it possible to navigate back to a component in Angular without having to reload it?

Within my Angular application, there is a main component that contains various child components. This main component includes logic for showing and hiding components based on certain conditions. <div *ngFor="let data of dataSource; let i=index"> & ...

Type Assertion in TypeScript Without Altering Original Data

Is there a preferred method for restricting a literal value in TypeScript to a specific type without sacrificing inferred type information? Let's say we have a type Named that must always contain a name. type Named = { name: string }; If we use a ...

When using react-hook-form within a .map() function, it encounters an issue causing it to fail - specifically, a TypeError message stating "Cannot read properties of undefined (reading '

Confused and frustrated here, I can't seem to get this form working properly. I have a Checkbox component that works fine when not in a loop, but as soon as I try to integrate it into a loop, everything breaks. Checkbox.tsx const Checkbox = React.for ...

DxDataGrid: Implementing a comprehensive validation system for multiple edit fields

I'm currently working with a DxDataGrid within an Angular Application. Within this particular application, I have the need to input four dates. I've implemented validation rules that work well for each individual field. However, my challenge aris ...

In Angular2, what serves the same purpose as a factory?

In my experience with Angular, I am accustomed to utilizing factories and services. As I delve into the Angular2 documentation, I cannot find any mention of a factory. Can someone tell me what the equivalent is in Angular2? ...

Having trouble dismissing Bootstrap alerts in TypeScript?

There seems to be an issue with the close button in a simple piece of code. The alert is displayed correctly, but clicking on the close button doesn't close the alert. Currently, I am using bootstrap 5.2.3. My code consists of a basic main file and an ...