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