【问题标题】:Angular : how to trigger bindings manually?Angular:如何手动触发绑定?
【发布时间】:2018-07-08 05:28:59
【问题描述】:

我有一个带有一组对象的角度材质 5 组件。它显示一个模式对话框,打开另一个组件,其中包含一个修改数组对象的表单。

当我的对话框关闭时,它会发回修改后的对象。所以父母接受这个结果并更新数组。但是显示器没有更新,这是我的问题。

是我的逻辑错误还是我需要手动重新触发绑定? 你有什么建议?

这里是打开对话框并在关闭后更新数组的函数。

openDialog(event: any, id: number) {
     const index = this.contractors.findIndex(x => x.Id === id); 

     const dialogRef = this.dialog.open(ContractorEditComponent, {
     width: '600px',
     data: { contractor : this.contractors[index] }
   });

   dialogRef.afterClosed().subscribe( (contractor: ContractorModel) => {
      if (contractor !== null) {
         this.contractors[index] = contractor; // update my collection with new value
         // Should I re-trigger data binding manually here to update the UI?
      }
   });
}

【问题讨论】:

标签: angular typescript data-binding angular-material


【解决方案1】:

Angular 的更改检测只会在引用新对象时触发,而在修改对象时不会触发。 使用this.contractors[index] = contractor,您只需修改数组,但引用本身保持不变。

有几种不同的方法可以解决这个问题,例如创建数组的新副本、使用Observables 或通过注入和使用ChangeDetectorRef 手动触发更改检测:

constructor(private ref: ChangeDetectorRef) {}
// ...
this.ref.detectChanges();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多