使用 ngOnChanges 检测两次分配相同值的属性 [英] Detect a property being assigned with the same value twice with ngOnChanges

查看:29
本文介绍了使用 ngOnChanges 检测两次分配相同值的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上我有一个对象数组,我想通过 @Input 将数组中选定对象的索引提供给另一个组件.

So basically I have an array of objects and I want to give the index of a selected object in the array to another component through @Input.

问题是,当两次选择相同的项目时,ngOnChanges 函数没有检测到更改,因为当我将值从 1 设置为 1 时,它不会将其识别为更改.. 这导致我无法连续两次选择同一个对象.

The problem is, when selecting the same item twice the ngOnChanges function doesn't detect a change since it doesn't recognize it as a change when I set the value from 1 to 1... This results in me not being able to select the same object twice in a row.

子组件:

@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 不会触发.

When the number stays the same, it isn't a new value, and thus OnChanges does not fire.

我不觉得传递带有索引的对象来解决这个问题太不方便.所以我建议如下:

I don't find it too inconvenient to pass an object with the index to resolve this issue. So I suggest the following:

editAppointmentIndex = {};

onEdit(i) {
  this.editAppointmentIndex = { index: i };
}

然后你会得到索引:

if (changes.editAppointmentIndex.currentValue && changes.editAppointmentIndex.currentValue.index != undefined) {
  console.log(this.editAppointmentIndex.index)
}

演示:StackBlitz

DEMO: StackBlitz

这篇关于使用 ngOnChanges 检测两次分配相同值的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆