Swaroop Babaleshwar
Swaroop Babaleshwar

Reputation: 211

how to update the object in child component when object property in changes in the parent component

I have 2 components

Parent component is

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

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

}

and child component is

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

   @Input() obj : any;

}

If I change any of the property in the obj in the parent, it is not getting updated in the child component.

Maybe because the obj reference is not changed.

Please suggest me the solution for this.

Upvotes: 1

Views: 1314

Answers (3)

Sivakumar Tadisetti
Sivakumar Tadisetti

Reputation: 5021

You have to use ngOnChanges like 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;
  }
}

Working example is here in Stackblitz

Upvotes: 1

Code Guru
Code Guru

Reputation: 15578

Use ngOnChanges to listen to changes of input properties. You will pass the object from parent to child and whenever there is any change in the object that you have passed as input to the child will give SimpleChanges object in ngOnChanges hook of child component.

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

Example

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

  ngOnChanges(changes: SimpleChanges) {
    // changes.prop contains the old and the new value...
  }
}

For more on ngOnChanges

Upvotes: 0

Krishna Rathore
Krishna Rathore

Reputation: 9687

Stackblitz Demo

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

  changeObject() {
    this.obj.name = 'Hello change';
  }

Upvotes: 0

Related Questions