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
Looping using ngFor and skip nth element
@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
<div *ngFor="let item of items; let i=index">
<div *ngIf="i != n">{{i}} is not n</div>
</div>
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 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
*ngFor="let item of items | slice:1 (without the comma) –
Lodhia
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
}
}
© 2022 - 2024 — McMap. All rights reserved.