Tips for synchronizing object updates between parent and child components in React applications

I have a dilemma with my 2 components:

The parent component looks like this:

@Component({
  selector: 'parent',
  template: `
    <child [obj]="obj"> </child>
  `,
  styleUrls: [''],
})
export class ParentComponent implements OnInit {

 obj = {
  id: 1,
  name: 'abc'
 }

}

And the child component is as follows:

@Component({
  selector: 'child',
  templateUrl: '',
  styleUrls: [''],
})
export class ChildComponent implements OnInit {

   @Input() obj : any;

}

My issue arises when I try to update the obj property in the parent component but it doesn't reflect in the child component.

I suspect the problem lies in the reference not being changed.

Can you please provide a solution for this?

Answer №1

To make changes in the object, utilize the ngOnChanges method as demonstrated below

Parent Component

export class AppComponent  {

  obj = {
    id:1,
    name:'abc'
  }

  name = 'Angular';

  changeObject() {
    this.obj.id++;
  }
}

Parent Template

<button (click)="changeObject()">Change Object</button>

<hello name="{{ name }}" [obj]="obj"></hello>

Child Component

import { Component, Input, OnInit, OnChanges } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1><p>{{ obj | json }}</p>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnInit, OnChanges { 
  @Input() name: string;
  @Input() obj;

  ngOnInit() {

  }

  ngOnChanges(changes) {
    this.obj = changes.currentValue ? changes.currentValue.obj : this.obj;
  }
}

Discover a functional demonstration here on Stackblitz

Answer №2

Check out the Stackblitz Demo

  data = {
    id: 1,
    name: 'Hello'
  }

  updateData() {
    this.data.name = 'Updated Hello';
  }

Answer №3

Utilize the ngOnChanges method to monitor changes in input properties. By passing an object from parent to child, any modifications to the passed input object will trigger the ngOnChanges hook in the child component, providing a SimpleChanges object.

interface OnChanges {
  ngOnChanges(changes: SimpleChanges): void
}

Illustrative Example

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnChanges {
  // Please address issue/24571: remove '!'.
  @Input()
  prop !: number;

  ngOnChanges(changes: SimpleChanges) {
    // Accessing changes.prop will reveal the previous and current values...
  }
}

For further details on ngOnChanges

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

Developing a dynamic object in Typescript to structure and optimize API responses

Currently Working Explanation: This is similar to the data array received from the API response responseBarDataStacked = [ { sku: "Data 1", month: "Jun", value: 20 }, { sku: "Data 2", month: "Jun", value: 25 ...

Exploring an Array of Arrays with jQuery

I have this code snippet and I am attempting to understand how to search through an array of objects where the call() function is invoked multiple times? var arr = []; var newData; function call() { newData = $('a').attr('href'); ...

Troubleshooting ngModel Binding Issue with Sub-Children in CKEditor 5 and Angular 7

Firstly, I am sharing my code below: ListPagesComponent: export class ListPagesComponent { public model = { id: -1, actif: 0, link: '', htmlContent: { fr: '', ...

Tips for incorporating external JavaScript code into React components

I have been tasked with integrating a graphical widget into a React component for a project I am working on. The widget_api code provided by RIPE Stat is required to accomplish this. Previously, in HTML5, the integration was successful using the following ...

Combining two elements in a React application

Having a collection of assets and their quantities: const bag = { eth: 50, btc: 30, kla: 10, set: 5, ova: 5 }; const assetList = { eth: { name: "Ethereum", icon: "urlhere", colour: "#030", text: "light&q ...

Develop a sophisticated multi-page application using create-react-app in conjunction with express.js

While I'm comfortable with back-end work, my front-end programming skills have gotten rusty. I used to work a lot with React, but it's been over a year since I last touched it. Recently, I started a project that requires me to refresh my knowledg ...

Clicking on the button will instantly relocate the dynamically generated content to the top of the page, thanks to Vue

Here is some dynamically generated content in the left column: <div v-for="index in total" :key="index"> <h2>Dynamic content: <span v-text="index + ' of ' + total"></span></h2> </div> There is also a butt ...

Execution of the RxJS pipe Finalize operator initiated prior to Observable finalization

After updating the detailed information of users, I attempted to retrieve the updated user list. Initially, I used this.mediaService.updateImports(): Observable<any> to update the user details. Next, I tried displaying the updated user details us ...

Turn off spellcheck for all material-ui elements

Is there a way to deactivate spellcheck globally for elements in the material-ui library? Before incorporating the material-ui library into my project, I used the code below to turn off spellcheck for all new DOM elements: const disableSpellCheck = funct ...

Open new tab for Angular OAuth2 OIDC login process

Currently, I am incorporating the authorization code flow using angular-oauth2-oidc in my Angular application. It is a fairly straightforward process. However, I would like to have the ability for the login flow to open in a new tab when the login button ...

Step-by-Step Guide: Crafting a Non-Ajax Popup Chat Application

Recently, I created a unique dating website with a one-to-one chat feature similar to Facebook. However, I implemented this using the ajax technique and the setInterval function in JavaScript for regular updates. Upon reflection, I believe that this appr ...

Avoid overwriting the success response parameter in jQuery Ajax

I've encountered a perplexing issue where the response parameter from the first ajax call is being overridden by the second call's parameter. Here is the code snippet: http://pastebin.com/degWRs3V Whenever both drawDonutForExternalLogin and dra ...

What could be causing the data storage issue in the state?

Using axios, I am fetching data and storing it in a state variable useEffect(() => { getCartItems(); }, []); const [abc, setAbc] = useState([]); const getCartItems = async () => { let data = await CartApi.get(`/${store.getState().auth.user.id}/ ...

Changing the position of an element in CSS using the center as the reference point, based on a JavaScript variable: How can it be done?

I have an image marking a scale, with the marker's position in HTML set as: <image class="red-marker" xlink:href="./assets/images/marker.png" [attr.x]=percentage width="12" height="40" y="0" ></image> But I want the middle of the marker ...

I am excited to create a Dynamic Routing system that selects specific elements from an array of objects using Typescript

1. crops-list.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-crops-list', templateUrl: './crops-list.component.html' ...

The creation of fsm.WriteStream is invalid as it is not a recognized constructor

Can you help me with this issue? I am attempting to install @ng-idle/keepalive using the command npm install --save @ng-idle/core, but I encountered the following error: npm ERR! fsm.WriteStream is not a constructor npm ERR! Log files were not written due ...

Preview your uploaded image before finalizing

I am currently working on implementing a new upload feature for users of our forum. This feature will allow them to upload a personal picture. Here is what I have developed so far: HTML <label>Profile image</label> <div class="phot ...

Repeating the same algorithms in both the back and front ends while applying Domain Driven Design

Within my class, I have some backend calculations: public class MyDomainClass{ private Double amount; private Double total; public Double getPercentage(){ /*business logic*/ } } I am using Angular 2+ for my frontend and I am looki ...

Unleashing the power of Sinon: a guide to covertly observing the e

I need to verify if the method "res.render" is invoked with the correct parameters. it("Checks if the page for creating a new user is rendered", done => { const spy = sinon.spy(ejs, "render"); chai .request(app) .get("/users/create ...

Combining all elements of my application into a single HTML, JS, and CSS file

My AngularJS app has a specific structure that includes different directories for each component: theprojectroot |- src | |- app | | |- index.html | | |- index.js | | |- userhome | | | |- userhome.html | | | ...