简体   繁体   English

如何将数据绑定到Angular 2中的数组?

[英]How do I data bind to arrays in Angular 2?

I'm trying to figure out how to data bind to arrays in Angular 2 so that changes are reflected. 我试图弄清楚如何将数据绑定到Angular 2中的数组,以便反映更改。 I have a sample todo app with an array property 我有一个带有数组属性的示例待办事项应用程序

get tasks(): TaskItem[] {
    return this.taskdb.tasks;
}

I would like to make updates efficient so I set changeDetection: ChangeDetectionStrategy.OnPush when the user adds a Task I use array.push to update the underlying data. 我想使更新更有效,所以我设置changeDetection:ChangeDetectionStrategy.OnPush当用户添加一个Task我使用array.push来更新底层数据。

add(task: TaskItem) {
    this.tasks.push(task);
}

The problem is because the array is the same reference (I don't want to clone and create a new array on every update), and the inputs to the component isn't changing, the UI doesn't update to reflect the change. 问题是因为数组是相同的引用(我不希望在每次更新时克隆并创建新数组),并且组件的输入不会更改,UI不会更新以反映更改。

Is there a way to do make Angular 2 update the UI on array update but without extraneous checks? 有没有办法让Angular 2在阵列更新时更新UI,但没有无关的检查?

ChangeDetection.OnPush expects your data to either be immutable or observable - array.push has nothing to do with it (bit of a confusing name there, I agree) ChangeDetection.OnPush期望你的数据要么是不可变的要么是可观察的 - array.push与它无关(那里有一个令人困惑的名字,我同意)

Changing the array reference might seem less efficient (and in terms of pure memory, it is...), but what it enables is immutable checking of the binding, which is more efficient. 更改数组引用似乎效率较低(就纯内存而言,它是......),但它启用的是不可变的绑定检查,这样更有效。

So this.tasks = this.tasks.concat([newTask]); 所以this.tasks = this.tasks.concat([newTask]); would make this work. 会使这项工作。 Otherwise, you'll need to use the regular change detection mechanism. 否则,您将需要使用常规更改检测机制。

Using changeDetection: ChangeDetectionStrategy.OnPush will need to pass a completely new reference to data input. 使用changeDetection:ChangeDetectionStrategy.OnPush将需要传递一个全新的数据输入引用。

So, instead of 所以,而不是

this.tasks.push(task);

use below 使用下面

this.tasks = [...this.tasks, task];

With this variation, it is not mutating the tasks array anymore, but returning a completely new one. 通过这种变化,它不再改变任务数组,而是返回一个全新的数组。 The things will start working again after this changes! 这些变化后,事情将再次开始工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM