angular - 在 Angular2 中过滤 NgFor

标签 angular angular2-template

我想显示数组的一些元素。 当使用管道过滤数组时,更新数组不会反射(reflect)在 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

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

最佳答案

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

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

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

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

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

希望对你有帮助 蒂埃里

关于angular - 在 Angular2 中过滤 NgFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35130961/

相关文章:

angularjs - Angular2 和 TSD 出现 "Duplicate identifier"错误

css - 什么是 `styles.css.less` 和 `styles.css.scss` 文件

typescript - 带有 TypeScript : Importing components into components 的 Angular2

Angular2 将纯文本转换为 url( anchor 链接)的方法

javascript - Angular2 组件 - 从索引页面呈现 html

Angular 2. 管道。无法读取未定义的属性

javascript - Angular 4 单元测试错误 - 无法在 'send' : Failed to load 'XMLHttpRequest' 上执行 'ng:///DynamicTestModule/LoginComponent.ngfactory.js'

html - 我想在我的 Angular login.Component.ts 中使用背景图片,但不显示

angular - 模板解析错误 : Can't bind to 'routerLink' since it isn't a known property of 'a'

javascript - ionic 2 : How do you reinstantiate @ViewChild if you dismiss the view?