jz87
jz87

Reputation: 9607

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. 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.

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.

Is there a way to do make Angular 2 update the UI on array update but without extraneous checks?

Upvotes: 3

Views: 2295

Answers (2)

Chintan Thummar
Chintan Thummar

Reputation: 1552

Using changeDetection: ChangeDetectionStrategy.OnPush will need to pass a completely new reference to data input.

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!

Upvotes: 0

robwormald
robwormald

Reputation: 863

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)

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]); would make this work. Otherwise, you'll need to use the regular change detection mechanism.

Upvotes: 3

Related Questions