3

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?

1
  • why don't you reference taskdb.tasks in the html file without using task() ... the changes on taskdb.tasks will be automatically applied on the UI Commented Dec 12, 2015 at 20:44

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to signal to the binding that the underlying data has changed even if the reference hasn't? I'm looking for an explicit binding signalling mechanism.
I found a solution after much digging into the API documentation. You have to implement the DoCheck interface to do manual update checking
@jz87 Can you provide an example?
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.