Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 ngFor over even/odd items

Tags:

angular

ngfor

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.

like image 665
EralpB Avatar asked Aug 09 '26 22:08

EralpB


1 Answers

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>
like image 165
Günter Zöchbauer Avatar answered Aug 11 '26 11:08

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!