【问题标题】:Detect a property being assigned with the same value twice with ngOnChanges使用 ngOnChanges 检测两次分配相同值的属性
【发布时间】:2019-08-19 21:26:12
【问题描述】:

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

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无法连续两次选择同一个对象。

子组件:

@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);
}

【问题讨论】:

  • 请提供minimal reproducible example,您说的是一个对象,但您已将editAppointmentIndex 定义为一个数字?
  • @AJT_82 对不起,我刚接触堆栈溢出,给我一秒钟,我将它定义为一个数字,因为我只传递数组中对象的索引号
  • @AJT_82 希望这就够了
  • 是的,这很完美:)

标签: angular typescript


【解决方案1】:

当数字保持不变时,它不是新值,因此OnChanges 不会触发。

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

editAppointmentIndex = {};

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

然后你会得到索引:

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

演示:StackBlitz

【讨论】:

  • 它告诉我类型错误:“changes.editAppointmentIndex.currentValue is undefined”,我该如何解决这个问题?
  • 应该是if (changes.editAppointmentIndex.currentValue &amp;&amp; changes.editAppointmentIndex.currentValue.index != undefined)
  • @Reza 应该在没有第一个 if 的情况下工作,因为我们已经初始化了 editAppointmentIndex(参见演示),但进一步考虑,我们可以添加第一个检查以防万一:) 谢谢
  • 感谢您的快速帮助和回复,现在可以正常使用
  • @AJT_82 changes.editAppointmentIndex.currentValue 据我所知与 editAppointmentIndex 不同,例如,如果投标变为空,则 currentValue 为空
【解决方案2】:

您也可以将@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;
}

【讨论】:

  • 你的例子有效。打开 f12 控制台。每次在 name1 和 name2 之间切换时都会输出 setfired。不是当你按两次相同的。我用火狐
  • 重点是 OP 希望 ngOnChanges 触发 即使值与之前的值相同,我们可以在演示中看到 setter 不触发时单击相同的值。
  • @JensAlenius,是的,尽管乍一看它似乎有效,但您的解决方案不起作用,所以当值再次设置为相同时,设置不会发生
  • 上述对象(AJT_82)的解决方案适用于setter
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-31
  • 1970-01-01
  • 2017-02-14
  • 2011-06-01
  • 2023-03-22
相关资源
最近更新 更多