简体   繁体   English

角度更新@Input() 对象

[英]Angular update @Input() Object

I've got a GameStats Object of my self defined interface.我有一个自定义接口的 GameStats 对象。 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.我找到了没有被解雇的 ngOnChanges 和仍然包含旧值的 ngDoCheck 的解决方案。

My example code:我的示例代码:

app.component.html app.component.html

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

app.component.ts (update attribute) app.component.ts(更新属性)

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

settings.component.ts settings.component.ts

@Input() gameStats!: GameStats;

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处理程序更改为:

  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.这会为this.gameStats分配一个新对象,该对象具有所有属性,但会覆盖gameRunning属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM