Philip John
Philip John

Reputation: 5565

Looping using ngFor and skip nth element

I was wondering if there is a way in angular2 to loop through an array or a list using *ngFor and skip the first or nth element

Upvotes: 12

Views: 26703

Answers (3)

Kwoque
Kwoque

Reputation: 291

I just learned from another issue, you can do it with Slice pipe

 *ngFor="let item of items | slice:1;

where 1 is your nth element

https://angular.io/api/common/SlicePipe

see also: Angular start ngFor index from 1

Upvotes: 12

Javier López
Javier López

Reputation: 119

You can use pipe in the loop like this:

html:

<ul>
  <li *ngFor="let element of object | values"> {{element}} </li>
</ul>

In the pipe element you can define everything that you want to control.
For example in pipe component (values.pipe.ts):

@Pipe({ name: 'values' })
export class ValuesPipe implements PipeTransform {
  transform(value, args: string[]): any {
    let values = []
    for (let key in value) {
      values.push(value[key])
    }
    return values
  }
}

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657338

<div *ngFor="let item of items; let i=index">
  <div *ngIf="i != n">{{i}} is not n</div>
</div>

Upvotes: 23

Related Questions