0

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

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

app.component.ts (update attribute)

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

settings.component.ts

@Input() gameStats!: GameStats;

1 Answers1

0

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.

Octavian Mărculescu
  • 4,312
  • 1
  • 16
  • 29
  • I tried something similar before to reassign the object. What do the '...' do? –  Jun 17 '22 at 12:29
  • It's called [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#spread_in_object_literals). It copies own enumerable properties from a provided object onto a new object. – Octavian Mărculescu Jun 17 '22 at 12:36
  • This is valid one, but worth noting that this could cause an issue with object copying. `Spread operator` only deep copies object when data is not nested. If your object contains nested data, it will make deep copy of top most data and shallow copy of nested data. – tony Jun 17 '22 at 12:57