问题
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