简体   繁体   English

对象变化的角度变化检测

[英]Angular Change Detection for Change in Object

I am trying to get ChangeDetection working properly in my Project.我正在尝试让 ChangeDetection 在我的项目中正常工作。

object-group.component.ts object-group.component.ts

objectGroup: ObjectGroup[];
...

doSomething() {
  objectGroup.forEach(item => {
    item.color = "new color";
  });
}

object-group.component.html object-group.component.html

<object-component *ngFor="let group of objectGroup"
    [object]="group">
</object-component>

object.component.ts对象.component.ts

@Input() object: ObjectGroup;

My question now is, why I am not getting informed, when changing properties inside an object?我现在的问题是,为什么在更改对象内的属性时我没有得到通知?

Thank you for answers!谢谢你的回答!

Here how you can check the object value changes在这里你可以如何检查对象值的变化

import { Component, DoCheck, KeyValueDiffers, HostListener } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements DoCheck {
  differ: any;
  objectGroup = []

  constructor(private differs: KeyValueDiffers) {
    this.objectGroup.forEach(item => {
      item.color = "new color";
    });
    this.differ = this.differs.find({}).create();
  } 
  ngDoCheck() {
    const change = this.differ.diff(this);
    if (change) {
      change.forEachChangedItem(item => {
        console.log('item changed', item);
      });
    }
  }
}

You are not getting informed because arrays and objects in JavaScript are held by reference and change detection will only kick in when the location in memory of the array and object changes.你没有得到通知,因为 JavaScript 中的数组和对象是通过引用保存的,只有当数组和对象在内存中的位置发生变化时,更改检测才会启动。 So to fix it, try to update it immutably.因此,要修复它,请尝试不可变地更新它。

Try:尝试:

objectGroup: ObjectGroup[];
...
doSomething() {
  // we change the location of `this.objectGroup` in memory by map and we change the
  // the location of each object in the array with the spread (...) and just changing
  // one property.
  this.objectGroup = this.objectGroup.map(item => ({...item, color: 'new color'}));
}

=============================== Edit ======================
// to change the location in memory of an object
this.obj = { ...this.obj };
// you can also change the object and change some of its properties
this.obj = { ...this.obj, prop1: 'new prop1 value' };

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

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