[英]angular10: How to detect complex input object in array change
我有一個數組,我使用 DoCheck 和 IterableDiffer 來監聽我的代碼中的變化。 當數組更改時,但當數組中的一個對象內的屬性更改時,我不會收到通知。 我嘗試對數組types
中的每個 object 使用 KeyValueDiffer ,但它在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);
}
})
}
}
在 Angular 中,更改檢測在分配時觸發。 這意味着您需要為綁定的變量或對象分配新值以觸發更改檢測。 因此,而不是僅更改對象的屬性。 之后嘗試重新分配數組以觸發檢測:
types = [...types];
在更新類型數組中的值時嘗試在父組件中分配它
<comp [types]="types"></comp>
本文可能會幫助您理解該概念: https://www.digitalocean.com/community/tutorials/angular-change-detection-strategy
首先要指出的是,這種變化檢測可能會不必要地昂貴和復雜。 我建議閱讀 RxJS 以及它如何處理數據變化。
但是,在您的具體示例中,問題不在於您的密鑰不同,而在於您如何處理readonly
的邏輯
在 javascript 中,原語(例如布爾值)不是通過引用傳遞,而是通過值傳遞。
這意味着當您設置以下內容時:
readonly: this.readonly
readonly type
中的值設置為 false,僅此而已。 如果稍后您更改this.readonly
,則type
中的值不會更改。 如果要保持兩個“實時”之間的連接,則需要通過引用傳遞,例如 object。 就像是
this.readonly = { status: false }
然后當你這樣做
this.readonly.status = true
該值也將在types
中更改。
這是一個 stackblitz 演示它的實際操作(並且不需要 keydiffers):
https://stackblitz.com/edit/angular-ivy-d8gige?file=src/app/app.component.ts
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.