The data passed into the child component via Input() retains its original value even after being modified within the child

While passing an object containing data length and an array of objects to a child component, I noticed a strange behavior. Even after changing the data in the child component and reloading the page, the edited property still persists.

To visualize this issue, please refer to the screenshots below:

  1. Upon initial navigation to the route, the data remains unmodified: https://i.sstatic.net/U9Wl9.png

  2. After editing the data: https://i.sstatic.net/qyz4a.png The right side shows the addition of the finalAmount property with its initialized value

  3. Upon returning to the same component, finalAmount is set to 5 https://i.sstatic.net/f8mSJ.png

The issue lies in the fact that the property should not be present in the data since it's inherited from the parent.

Below are the relevant files:

  1. stepper.component.html (Parent Component)
<mat-step [stepControl]="thirdFormGroup" >
        <ng-template matStepLabel>Prepare Invoice</ng-template>
        <ng-template matStepContent>
            <div class="container-fluid">
            
                <app-create-invoice [selectedCustomersInfo]="selectedCustomerData"
                    [selectedProductsData]="{lengthOfData:cartItems.length , selectedProducts:cartItems}"></app-create-invoice>
            
            </div>
        </ng-template>
    </mat-step>
  1. stepper.component.ts:
...
  1. create-invoice.component.html (Child Component):
...
  1. create-invoice.component.ts:
...

The persisting of properties like finalAmount, discount, and sgst even after editing raises concerns. Any assistance would be greatly appreciated.

Answer №1

It seems like you're encountering a common issue in Angular where changes made to data in a parent component are not automatically reflected in a child component that received the data through @input(). To address this, familiarize yourself with Angular's lifecycle hooks by clicking on this link: HERE. Implementing change detection hooks in your code is essential for resolving this issue.

@Input() someInputData: any;
    
ngOnChanges(changes: SimpleChanges) {    
    this.doSomething(changes.someInputData.currentValue);
}

Alternatively, you can use a getter-setter approach like this:

private _someInputData: string;

@Input() set someInputData(value: any) {
   this._someInputData = value;
   this.doSomething(this._someInputData);
}

get someInputData(): any {
    return this._someInputData;
}

Both approaches have their merits, but the choice between them may depend on the specific requirements of your application. While ngOnChanges() allows you to compare current and previous values, it also tracks all inputs, unlike the getter-setter approach.

In some cases, particularly with nested objects, change detection in Angular can be challenging. For a more comprehensive solution, refer to this link: SOLUTION

EDIT! After considering your feedback, it appears that the issue you're facing is related to how objects are handled in Angular. When passing an object through the @Input() decorator, a copy of the object with all its references is created. To address this, you need to create a deep copy of the object and its nested objects to avoid lingering references. While using Object.assign() may work, an alternative approach is to try the following:

const tempClone = JSON.parse(JSON.stringify(productsData));

Answer №2

Using structuredClone() is a reliable method for creating deep copies of nested objects, particularly when dealing with objects containing arrays.

Take a look at the screenshot provided for visual reference: https://i.sstatic.net/v9ly8.png

It's important to note that

JSON.parse(JSON.stringify(productsData))
comes with its own set of limitations.

For further information, please check out the following links:

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 method for determining the cookie expiration time in AngularJS 1.3?

Currently in my application, I am utilizing AngularJS 1.3. I encountered a challenge while using $cookies to store data where I needed to implement a 1-minute expiration time for the cookie. However, the $cookies service in AngularJS 1.3 does not provide ...

Having trouble with installing the most recent versions of React App dependencies

After cloning a project from GitHub, I attempted to install dependencies using npm install, but encountered an error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email ...

I encountered an error in the console stating, "Uncaught ReferenceError: req is not defined," while trying to access req.query.id

Encountering the error 'Uncaught ReferenceError: req is not defined' when attempting to use req.query.id. Below is the content of my index.js file: const express = require("express"); const path = require("path"); const port = 8000; ...

Which method is optimal for organizing tree categories and linking them to posts, as well as locating posts based on a selected category within a MERN stack

Currently, I am utilizing the MERN stack for my project development. The project involves a tree category structure as outlined below: {id: { type: Number }, parent_id: { type: Number }, name: { type: String }, sub: { type: Boolean }} For ...

The ng test option is failing to execute effectively

Attempting to conduct unit tests utilizing Karma and Jasmine through the ng test is proving to be a bit challenging. Upon issuing the following command: ng test --watch=false --code-coverage --main ./src/main/resources/public/scripts/xyz/workspace/commons ...

Using ng-repeat can cause conflicts with jQuery function calls

I implemented a combination of AngularJS and MaterializeCSS to display images using ng-repeat. MaterializeCSS comes with a jQuery-based materiabox function that triggers an animation to open a modal for each element with the materialbox class. However, I ...

Convert text into a clickable link

Creating a form with numerous text fields, some of which require numerical input. The main goal is to have users enter a tracking number, order number, or any other type of number that, when submitted, will open a new URL in a separate window with the spec ...

Emails can be sent through a form without the need for refreshing

I am currently working on a webpage that utilizes parallax scrolling, and the contact box is located in the last section. However, I encountered an issue where using a simple HTML + PHP contact box would cause the page to refresh back to the first section ...

Using VBA to Populate Dropdown List on Webpage from an iFrame

I am facing an issue with my code that aims to interact with a webpage by clicking on a link and then modifying dropdown lists within an Iframe. Specifically, I am attempting to populate the Manufr dropdown list based on data from the Year iFrame using VBA ...

Generating a dynamic sitemap with Next.js

I have been working on a project where I need to create a sitemap, and I am currently using next-sitemap for generation. However, I've encountered an issue with this method, as well as other solutions I've come across, because the sitemap is only ...

ES6 scoping confusion: unraveling the mystery

I stumbled upon these two syntax methods for exporting functions. Let's say we have files named actions.js and app.js. The first method looks like this: in actions.js export function addTodo() {} export function deleteTodo() {} and in app.js I have ...

Oops! There was an issue trying to solve the command "/bin/bash -ol pipefail -c npm run build" while deploying a Next.js app on Railway. Unfortunately, it did not complete successfully and returned an exit code of

[stage-0 8/10] RUN --mount=type=cache,id=s/8a557944-4c41-4e06-8de9-06bfcc5e8aaf-next/cache,target=/app/.next/cache --mount=type=cache,id=s/8a557944-4c41-4e06-8de9-06bfcc5e8aaf-node_modules/cache,target=/app/node_modules/.cache npm run build: 17.62 17.62 ...

Is it possible to bring in a `devDependency` into your code?

The Mobx DevTool's README instructs users to install it as a dev dependency, and then import it into their code. This approach raises concerns for me because devDependencies are typically reserved for tools used in the build process or managing end co ...

Having trouble with the JSON format within the 'operations' field in the formData of your Next.js application?

I encountered a mutation that looks like this- mutation signUp($avatar: Upload!) { signUp( avatar: $avatar input: { name: "Siam Ahnaf" email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

on clicking GTM, obtain a different child element

My HTML code is structured as follows: <div onclick="location.href='https://ford-parts-accessories.myshopify.com/products/ash-cup-coin-holder-with-lighter-element?refSrc=6748959244479&amp;nosto=productpage-nosto-1-fallback-nosto-1';&q ...

Struggling with setting up Role-Based Access Control (RBAC) with cookie authentication in React

I've been working on incorporating Role Based Access Control into a React app using cookies, but I'm struggling to understand its use. The idea was to create a context that retrieves the data stored in the cookie through a specific API endpoint d ...

Steps for setting up node-openalpr on a Windows 10 system

While attempting to install npm i node-openalpr, an error is occurring: When using request for node-pre-gyp https download, I encounter a node-pre-gyp warning and error message. The package.json for node-openalpr is not node-pre-gyp ready, as certain pr ...

Utilizing a powerful combination of Angular 5, PrimeNG charts, Spring Boot, and JHipster

I am facing an issue with creating charts using PrimeNG. The main challenge I'm encountering is the conversion of data from a REST API in Angular 5 (TypeScript) and retrieving the list of measurements from the API. I have an endpoint that returns my m ...

What is the process of overriding a method from an abstract class that employs generics for typing?

In my quest to develop an abstract class with an abstract static method, I find myself wanting to override this method in a concrete class. The static nature of the method stems from its responsibility to create a 'copy' from a database model and ...

Issue with Vuetifyjs theme variable failing to function properly in version 1.0.0

Check out the step-by-step instructions provided in https://vuetifyjs.com/en/style/theme. I successfully changed the theme using the code below with vuetifyjs version 0.13.0. However, after updating to vuetifyjs 1.0.5, the font still displays correctly bu ...