我在这里找到了一些答案,人们建议使用与此类似的一行代码:
<div *ngFor="let x of filter(myArray)">
但是,filter(myArray)
一直运行。
我发现像下面这样保留 2 个数组会更有效率。
<div *ngFor="let x of filteredArray">
代码
let fullArray = [1,2,3,4,5,6]
let filteredArray = []
onFilterEvent() {
filteredArray = fullArray.filter(x => /* filtering logic */)
}
这里的缺点是我不断地重写 filteredArray
的内容。但是,它仅在需要过滤逻辑时才运行,而不是一直运行。
有没有理由使用第一种方法?它仍在做同样的工作,但它会一遍又一遍地做。
最佳答案
出于性能的原因,Angular 建议将过滤和排序逻辑移至组件本身。您应该在组件内部进行过滤,而不是不断运行管道或函数:
The Angular team and many experienced Angular developers strongly recommend moving filtering and sorting logic into the component itself. The component can expose a filteredHeroes or sortedHeroes property and take control over when and how often to execute the supporting logic. Any capabilities that you would have put in a pipe and shared across the app can be written in a filtering/sorting service and injected into the component.
https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
关于javascript - 在 ngFor 中使用过滤器函数有好处吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45535717/