【问题标题】:Unexpected binding in Angular 2Angular 2 中的意外绑定
【发布时间】:2017-06-08 14:58:01
【问题描述】:

我在使用 PrimeNG DataTable 的 Angular 2 应用程序中遇到了一个非常奇怪的问题。可以使用[editable]"true" 语法更改我的DataTable 中的数据。

DataTable 中的数据称为 =inschrijvingen。 我正在做this.originalInschrijvingen = this.inschrijvingen 在用户更改数据之前创建一个“副本”,以便我可以在稍后阶段比较更改。但由于某种原因,DataTable 数据绑定到originalInschrijvingeninschrijvingen

这是我的代码:

onRowSelectUser(event) { //This is a different DataTable than the editable DataTable
    this.getGebruikerZijnInschrijvingen(res => {
      this.createRoleID(res => {
        let selectedIds = this.gebruikerZijnInschrijvingen.map(it => it.DefUnitID);
        this.selectedInschrijvingen = this.inschrijvingen.filter(inv => selectedIds.indexOf(inv.ID) != -1);
        this.originalInschrijvingen = this.selectedInschrijvingen;
      })
    })
  }

【问题讨论】:

  • 也许阅读编程中的参考资料会有所帮助。 en.wikipedia.org/wiki/Reference_(computer_science)
  • 谢谢!我不知道它是引用而不是“复制”。谢谢!
  • @Pengyy 感谢您的回复,但我想我已经找到了答案 = Link
  • @Milan_w 好的,对我来说,我建议您避免使用该链接中提到的json.parsejson.stringify 的方式可能会导致问题。
  • @Pengyy 好的,我会调查您的解决方案!谢谢!

标签: angular typescript data-binding datatable


【解决方案1】:

this.selectedInschrijvingen 似乎是一个数组,在 Javascript 中,当您使用 = 运算符将一个数组分配给另一个数组时,它们是通过引用复制的,因此它们代表相同的数组。

你可以在下面做,

this.originalInschrijvingen = this.selectedInschrijvingen.slice();

slice() 方法返回数组一部分的浅拷贝 进入从开始到结束(不包括结束)选择的新数组对象。 原数组不会被修改。

希望这会有所帮助!

【讨论】:

  • 谢谢你的解释!!至少我现在明白为什么会这样了,这让我发疯了!但是您的解决方案不太有效,它仍然更新两个数组?还有什么想法吗?
  • 我找到了一种方法来做到这一点。 This guy 有一个没有任何赞成的想法,但它似乎对我有用。
猜你喜欢
  • 2016-08-05
  • 2016-07-22
  • 2017-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多