Looping using ngFor and skip nth element
Asked Answered
G

3

12

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

Gagarin answered 21/2, 2017 at 16:18 Comment(2)
@aloisdg It is not really a duplicate, as it is asking for skipping 1st element. I am asking for nth element in general. The answers are also way different.Gagarin
Indeed. My close is retracted. (I will delete this comment too)Yerxa
C
23
<div *ngFor="let item of items; let i=index">
  <div *ngIf="i != n">{{i}} is not n</div>
</div>
Collier answered 21/2, 2017 at 16:19 Comment(2)
How can I skip each Nth element, like each 3d or each 2d?Epos
Sure, you can use the modulo operator % developer.mozilla.org/en/docs/Web/JavaScript/Reference/… like *ngIf="i % 3 != 0". i will still count them. You can also use a pipe that returns an array that doesn't contain these elements, then i will match the number of visible elements, not the number of source elements.Egan
A
12

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

Anatolian answered 29/2, 2020 at 13:15 Comment(1)
*ngFor="let item of items | slice:1 (without the comma)Lodhia
T
1

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
  }
}
Tombac answered 28/2, 2020 at 8:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.