Home > Software design >  Child component updates parent then parent updates another child component's Input value
Child component updates parent then parent updates another child component's Input value

Time:07-22

I know this question might have been asked dozens of times here, but I've reached all the approaches and I still can get it to work (I've tried with a subscription on the child and ngOnchanges)

So this is the basic structure of my project's issue: enter image description here

Template on parent

<child-a (updateParentOnSave)="updateOnSave($event)"></child-a>
<child-b [myObjectData]="myObjectData"></child-b>

On Child A:

After calling a certain method I emit this value to the parent component

this.updateParentOnSave.emit({ someFlag: false, myData: this.myData });

On Parent

 updateOnSave(updateData: any): void {
      this.someFlag = updateData.someFlag;
      // Update the child data
      this.myObjectData = {...updateData.myData}; // Using spread operator since the received data is an object.
    }
  }

Up to this point, everything works, fine I can see the value of updateData.myData on the parent where this.myObjectData is the @Input value on Child B

On Child B

Here I have a certain non-relevant method, that once it is called should used the value of this.myObjectData And this is what I have so far:

myData: any;
@Input() myObjectData: any;

  ngOnChanges(changes: SimpleChanges): void {
    if (this.myObjectData) { // Added this to avoid the initial undefined
      this.myData= changes.myObjectData.currentValue;
    }
  }

  // This method is only called after the @Input myObjectData was updated on the parent
  someInvokedFunction(): void {
    console.log(this.myData); // THIS RETURNS UNDEFINED ALWAYS
  }

So I've tried everything, even using a getter/setter and it never works I keep getting undefind when someInvokedFunction gets called.

Am I missing something here?

CodePudding user response:

The problem is here,

  ngOnChanges(changes: SimpleChanges): void {
    if (this.myObjectData) { // Added this to avoid the initial undefined
      this.myData= changes.myObjectData.currentValue;
    }
  }

I think you probably meant to put changes.myObjectData.

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.myObjectData) { // Added this to avoid the initial undefined
      this.myData= changes.myObjectData.currentValue;
    }
  }

Here is the documentation regarding that hook in case you're curious when and why it fires.

  • Related