2

我想显示数组的一些元素。使用管道过滤数组时,更新数组不会反映在 DOM 中,如下面的代码所示。

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

这个问题似乎是因为数组过滤器方法创建了一个新数组。如何在不破坏数据绑定的情况下过滤数组?

4

1 回答 1

2

您需要更新数组本身的引用。我的意思是对象内的更新不会触发更改检测,但如果您更新整个引用,它会触发。

您可以change像这样更新方法的代码:

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

这是更新的 plunkr:https ://plnkr.co/edit/g3263HnWxkDI3KIhbou4?p=preview 。

这是另一个可以帮助您的答案:

希望它可以帮助你,蒂埃里

于 2016-02-01T12:50:12.907 回答