Angular 2 ngFor over even/odd items

假如想象 提交于 2020-01-02 08:35:20

问题


I have a list with 2 columns, I want the left to show even indices and right to odd.

Currently I'm iterating the whole list for every column and filtering with ngIf="odd" or even.

Can I make ngFor only do and watch even or odd indices?

Would that improve the performance drastically? I don't know how much of a burden is it when half of the DOM elements are ng-if'ed out.

The list doesn't change frequently but when it changes it changes completely.


回答1:


You can create a pipe that only returns odd or even items

@Pipe({ name: 'evenodd' })
export class EvenOddPipe implements PipeTransform {
  transform(value:any[], filter:string) {
    if(!value || (filter !== 'even' && filter !== 'odd')) {
      return value;
    }
    return value.filter((item, idx) => filter === 'even' ? idx % 2 === 1 : idx % 2 === 0 );
  }
}

and use it like

<div *ngFor="let item of items | evenodd:'even'"></div>    
<div *ngFor="let item of items | evenodd:'odd'"></div>


来源:https://stackoverflow.com/questions/40729757/angular-2-ngfor-over-even-odd-items

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!