![](/img/trans.png)
[英]ngOnChanges not getting called twice although we are changing the value of property twice in parent component
[英]Detect a property being assigned with the same value twice with ngOnChanges
所以基本上我有一個對象數組,並且我想通過@Input
將數組中所選對象的索引提供給另一個組件。
問題是,當兩次選擇同一項目時, ngOnChanges
函數不會檢測到更改,因為當我將值從1設置為1時,它不會將其識別為更改...這導致我無法選擇同一對象連續兩次。
子組件:
@Input('editAppointmentIndex') editAppointmentIndex: number;
ngOnChanges(changes: SimpleChanges) {
console.log(changes);
if (changes.editAppointmentIndex && changes.editAppointmentIndex.currentValue != undefined) {
// Do what i want to do with the selected object
}
}
父組件:
<child-component [editAppointmentIndex]="currentAppointmentIndex"></child-component>
currentAppointmentIndex: number;
onEdit(i) {
this.currentAppointmentIndex = i;
}
兄弟組件:
<button class="edit" (click)="onEdit(i)">Edit</button>
@Output() onEdit_: EventEmitter<number> = new EventEmitter<number>();
onEdit(i) {
this.onEdit_.emit(i);
}
當數字保持不變時,它不是新值,因此不會觸發OnChanges
。
我發現傳遞帶有索引的對象來解決此問題不是很麻煩。 所以我建議如下:
editAppointmentIndex = {};
onEdit(i) {
this.editAppointmentIndex = { index: i };
}
然后您將獲得具有以下內容的索引:
if (changes.editAppointmentIndex.currentValue && changes.editAppointmentIndex.currentValue.index != undefined) {
console.log(this.editAppointmentIndex.index)
}
演示: StackBlitz
您也可以將@Input與setter一起使用
oldValue:number;
@Input()
set editAppointmentIndex(value: number) {
if (value&&value!=this.oldValue) {
// Do what i want to do with the selected object
}
this.oldValue = value;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.