Reimer
Reimer

Reputation: 23

Filtering NgFor in Angular2

I want to display some of the elements of an array. Updating the array does not get reflected in the DOM when the array has been filtered with a pipe as the following code demonstrates.

import {Component} from 'angular2/core'
import {Pipe, PipeTransform} from 'angular2/core';

@Pipe({name: 'myPipe'})
export class MyPipe implements PipeTransform {
    transform(numbers) {
        return numbers.filter(n => n > 2);
    }
}

@Component({
  selector: 'my-app',
  template: `
    <button (click)="change()">Change 3 to 10</button>
    <ul> <li *ngFor="#n of numbers | myPipe">{{n}}</li> </ul>
    <ul> <li *ngFor="#n of numbers">{{n}}</li> </ul>
  `,
  pipes: [MyPipe]
})
export class App {
  numbers = [1, 2, 3, 4];

  change() {
    this.numbers[2] = 10;
  }
}

https://plnkr.co/edit/1oGW1DPgLJAJsj3vC1b1?p=preview

This issues seems to occur because the array filter method makes a new array. How can I filter the array without breaking the data binding?

Upvotes: 2

Views: 1734

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202326

You need to update the reference of the array itself. I mean updates within objects don't trigger change detection but if you update the whole reference, it does.

You could update the code of your change method like that:

change() {
  this.numbers[2] = 10;
  this.numbers = this.numbers.slice();
}

Here is the updated plunkr: https://plnkr.co/edit/g3263HnWxkDI3KIhbou4?p=preview.

Here is another answer that could help you:

Hope it helps you, Thierry

Upvotes: 2

Related Questions