Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular update @Input() Object

I’ve got a GameStats Object of my self defined interface. If I change the value of a attribute the child component doesn’t recognize it.
I found solutions with ngOnChanges which doesn’t get fired, and with ngDoCheck which still contains the old values.

My example code:

app.component.html

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<app-settings [gameStats]="gameStats"></app-settings>

app.component.ts (update attribute)

  onRunningStatusChanged(event: any) {
      this.gameStats.gameRunning = event;
  }

settings.component.ts

@Input() gameStats!: GameStats;

>Solution :

Change detection doesn’t do deep object comparison, it only checks if the reference is the same, and in your case it is. You might want to change the onRunningStatusChanged handler to this:

  onRunningStatusChanged(event: any) {
      this.gameStats = {...this.gameStats, gameRunning: event};
  }

This assigns a new object to this.gameStats that has all the properties, but with the gameRunning property overwritten.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading