gpt4 book ai didi

angular - 使用 ngOnChanges 检测两次分配相同值的属性

转载 作者:搜寻专家 更新时间:2023-10-30 21:20:57 28 4
gpt4 key购买 nike

所以基本上我有一个对象数组,我想通过 @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

关于angular - 使用 ngOnChanges 检测两次分配相同值的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57556856/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com