我有一个数组,我使用DoCheck和IterableDiffer来侦听代码中的更改。当数组被更改时,但是当数组中的一个对象中的一个属性发生变化时,我将不会收到通知。我尝试对数组KeyValueDiffer中的每个对象使用types,但它在ngDoCheck中不起作用。有什么想法吗?
在父母中:
<comp [types]="types"></comp>readonly: boolean = false;
types: {
readonly: boolean;
title: string;
value: any;
}[] = [{
title: 'title1',
readonly: this.readonly,
value: 1
}, {
title: 'title2',
readonly: this.readonly,
value: 2
}];
ngOnInit() {
setTimeout(() => {
this.readonly = true;
}, 5000)
}在组件comp中
constructor(
private differsService: KeyValueDiffers
) {};
@Input() types: any[] = [];
ngOnInit() {
this.differ = this.searchTypes.reduce((t, c, i) => {
t[`types_${i}`] = this.differsService.find(c).create();
return t;
}, {});
}
ngDoCheck(): void {
if (this.differ) {
Object.keys(this.differ).map((key: string) => {
const k = key.split('_');
const state = k.length === 1?this[k[0]]:this[k[0]][k[1]];
const changes = this.differ[key].diff(state);
if (changes) {
console.log(key, changes);
}
})
}
}发布于 2022-09-02 09:52:30
首先要指出的是,这种变化检测可能不必要地昂贵和复杂。我建议阅读RxJS以及它如何处理数据更改。
然而,在您的具体示例中,问题不在于您的密钥不同,而在于您处理readonly的逻辑
在javascript中,原语(如booleans)不是通过引用传递,而是通过值传递。
这意味着当您设置以下内容时:
readonly: this.readonly
type中的readonly值设置为false,仅此而已。如果稍后更改this.readonly,则不会更改type中的值。如果您希望保持两个“活动”之间的连接,则需要通过引用传递,例如,使用一个对象。就像这样
this.readonly = { status: false }
当你这么做的时候
this.readonly.status = true
该值也将在types中更改。
这里有一个stackblitz演示了它的作用(不需要键):
https://stackblitz.com/edit/angular-ivy-d8gige?file=src/app/app.component.ts
发布于 2022-09-02 09:21:12
在角度上,变化检测是在分配时触发的。这意味着需要为绑定变量或对象分配新值以触发更改检测。所以,不要只更改对象的属性。之后再重新分配数组以触发检测:
types = [...types];在更新类型数组中的值时,尝试在父组件中分配该值。
<comp [types]="types"></comp>本文可能会帮助您理解这个概念:https://www.digitalocean.com/community/tutorials/angular-change-detection-strategy
https://stackoverflow.com/questions/73580034
复制相似问题