0

I want to modify the @Input() object values in child component after every change in parent component. Please find the sample example

In below example, I increment the counter from parent component and passing complete object to child component. then, I am modifying the counter and storing in new value. it is not working. If I pass only counter as primitive then it is working perfectly fine. But, not working when passing object. Please assist.

<<PARENT COMPONENT -- app.component.ts>>

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  <hello [dataObject]="dataObj"></hello>
  <button (click)="inc()">INCrease</button>  
  `  ,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  dataObj = {"counter": 1, "info":"Welcome to party"};

  public inc(){
    this.dataObj.counter++;
  }
}

<< CHILD COMPONENT -- hello.component.ts>>
import { Component, Input, SimpleChanges } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{_couter}}!</h1>
  `
})
export class HelloComponent {
  _couter: any;

  @Input() dataObject: any;

  // @Input()
  // public set dataObject(val) {
  //   console.log('set Name: ', val);
  // this._couter = val.counter + " count"
  // }
  
  ngOnChanges(changes: SimpleChanges) {
    console.log("changes", changes);
    if(changes.dataObject){
      //Wanted to perform some operation on counter data then render on screen
      //can not directlly modify data on html template 
      console.log("changed dataObject", changes.dataObject)
      this._couter = changes.dataObject.currentValue.counter + " count"
    }
  }

}


user3340927
  • 25
  • 1
  • 5

0 Answers0