本文介绍了Angular 2 ng适用于奇数/奇数项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含2列的列表,我希望左边显示偶数索引,右边显示奇数.

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

目前,我正在遍历每列的整个列表,并使用ngIf ="odd"甚至偶数进行过滤.

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

我可以使ngFor只做并观看偶数或奇数索引吗?

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

会大大提高性能吗?我不知道如果将一半的DOM元素ng-if'ed出来会给您带来多大的负担.

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.

推荐答案

您可以创建仅返回oddeven项的管道

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 );
  }
}

并像使用它

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

这篇关于Angular 2 ng适用于奇数/奇数项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 03:26