What is the reason for the manual update of a view when copying an object's attributes into another object, as opposed to using Object.assign()?

In my application, I have a parent component called 'EmployeeComponent' that is responsible for displaying a list of employees. Additionally, there is a child component named 'EmployeeDetailComponent' which displays the details of the selected employee such as their name and email.

To pass the selected employee from the parent to the child component, I am using an @Input decorator like so:

@Input() employee: Employee; // This line should be included in the child component

The child component allows users to edit the employee information. Upon editing, the updated employee object is then passed back to the parent component using an event emitter defined as follows:

In the child component:

@Output() onSaved = new EventEmitter<Employee>();
onSubmit(){
    this.onSaved.emit(this.employee);
}

And in the parent component:

onSaved(employee: Employee){

    // The following line does not affect the employee's details in the view
    this.selectedEmployee = Object.assign({}, employee);

    // However, the old values are successfully replaced by the new ones
    console.log(this.selectedEmployee);

    // Additionally, this line successfully changes the employee's details in the view
    this.employee.name = employee.name;

}

My question pertains to the differing outcomes of these two methods. Both approaches seemingly change the employee's details, yet only the second method seems to reflect these changes in the view. Why is that?

Answer №1

The Object.assign() method always returns the original object instance. When it comes to Angular's change detection mechanism, it only focuses on comparing object identities rather than their actual contents.

This means that if you have a different object with identical properties and values, Angular will still detect it as a change and trigger a re-render of the view.

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

Leveraging vuex in conjunction with typescript allows for efficient management of state in namespace modules,

I am currently integrating vuex with typescript and namespaces module in my project. Within this setup, I have two distinct modules: "UserProfile" and "Trips". So far, everything is functioning smoothly within the confines of each module. However, I have ...

Angular 2 now has the ability to detect keydown events triggered from any part of the page

Is there a way to enable keyboard control for a view? I attempted using document.keydown, but it wasn't successful. How can I make the document accept keyboard input? A solution that worked for me was implementing this in my component class: @HostLi ...

User interface designed for objects containing multiple keys of the same data type along with a distinct key

I have a question that relates to this topic: TypeScript: How to create an interface for an object with many keys of the same type and values of the same type?. My goal is to define an interface for an object that can have multiple optional keys, all of t ...

Is there a way to specialize generic methods in Typescript and make them more specific?

I am working with a generic static method in an abstract class: abstract class Base { static find<T extends Base>(options?: Object): Promise<T[]> { return findResults(options); } } Now, I am trying to specify its type in a derived cla ...

Validation of email forms in Angular 5

I have encountered a challenge that I need help with: Using Angular 5 - template driven form In my template, there is an input field with the type email. Here's an example: <input type="email" [(ngModel)]="model.email" #email="ngModel" email /> ...

Unexpected behavior: ng2-dragula modelDrop event leading to undefined array

Struggling to figure out the issue with this code. As shown in this GIF, when dragging a div from one container to another, the object disappears and the array becomes undefined. https://i.stack.imgur.com/TELyc.gif Here is the code snippet: Main View.ht ...

What is the best way to integrate Tawk.to into a React application while using typescript?

Having some issues integrating tawk.to into my website built with React and TypeScript. I have installed their official npm package, but encountered an error message: import TawkMessengerReact from '@tawk.to/tawk-messenger-react'; Could not fin ...

Is it possible for me to modify the appearance of the ion-searchbar in Angular?

Currently working on an angular ionic project and I'm looking to personalize the design of the ion-searchbar. In the default template, the search bar icon is positioned on the left side. My goal is to adjust the placement of the icon and have it situa ...

Angular 2: Issue with data table not updating after item deletion

I need assistance with updating a data table after deleting an item. The database is updated correctly when I delete an item, but the table does not automatically refresh to reflect the changes. managenews.component.ts import { Component, OnInit } from ...

When working with Angular/Typescript, the error message "compilation of 'export const' is not possible

Embarking on creating my very own Angular library, I took the first step by adding a service without any issues. The challenge arose when I decided to move a constant to a file named tokens.ts for the service to reference. Following this change, the build ...

Obtaining a document using Angular and Spring MVC API

Having trouble downloading a file upon clicking a button using Angular. The downloaded file is showing as 0 KB in size and won't open. This is the code snippet I'm currently using with Angular and Spring MVC: Angular : public downloadFile(file ...

Error thrown due to syntax issues in react.d.ts declaration file in TypeScript

Currently, I am attempting to integrate react with typescript in my project. However, typescript is generating syntax errors for the react.d.ts file sourced from Github: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/react The encountered ...

Create an array filled with multiple arrays containing objects

To achieve the desired array of array of objects structure, I need to populate the data like this: let dataObj = [ [ { content: "test1"}, { content: "test2"}, { content: "test3"} ], [ ...

Tips for preventing my component from being duplicated during the development process

I found a helpful guide on creating a JavaScript calendar in React that I am currently following. After implementing the code, I successfully have a functional calendar UI as shown below: // https://medium.com/@nitinpatel_20236/challenge-of-building-a-cal ...

Error Message: Unable to access 'map' property of undefined in TSX file

Component for displaying attendees in an activity interface IProps { attendees: IAttendee[] } export const ActivityListItemAttendees: React.FC<IProps> = ({attendees}) => { return ( <List horizontal> {attendees.ma ...

How can an Angular Component be created in the browser using the standard method?

Attempting to develop a basic Angular example using JS/ESM. It has been some time since working within the angular environment, and there appear to be two primary choices: Utilizing the UMD lib (preferably to be avoided) Using the ESM2015 folder and loadi ...

Error encountered during Typescript compilation: The attribute 'raw' is not found within the context of the entity 'e' in express

In many instances, I have noticed that people use express.raw() or express.raw({type: 'application/json'}) as middleware in their requests... but is .raw() a legitimate method in Express? I am currently working with TypeScript and using Express ...

What is the best approach in Typescript to ensure type understanding when importing using require()?

Currently, I am working with TypeScript within IntelliJ. Let's say I have the following code: const functions = require('firebase-functions'); Then I proceed to use it in this manner: exports.doSomething = functions.https.onCall((data, c ...

Troubleshooting: Issue with Angular 2 bidirectional data binding on two input fields

Hi there, I am encountering an issue with the following code snippet: <input type="radio" value="{{commencementDate.value}}" id="bankCommencementDateSelect" formControlName="bankCommencementDate"> <input #commencementDate id="bankCommencementDat ...

Why is it that PowerShell cannot execute Angular commands?

Recently, I started diving into Angular and encountered an issue using PowerShell in Windows. Every time I run an angular command like: ng new new-app or ng serve I keep getting this error message: ng : File C:\Users\< username >\ ...