Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - How to handle an *ngFor when you want to show "1st", "2nd", "3rd", etc.?

Tags:

angular

I am trying to create a loop to show a few divs, between one and seven.

However, each div will have a <p> Pick your 1st photo </p>, where the first item will say 1st, the second 2nd, third 3rd, etc.

How can I handle something like this?

<div *ngFor="let item of items">
  <p>Pick your ___ photo</p>
</div>

Thanks

like image 933
user1354934 Avatar asked Sep 13 '16 23:09

user1354934


2 Answers

Use index within *ngFor and then transform one-more-than-the-index with an ordinal pipe:

<div *ngFor="let item of items; let i = index">
    <p>Pick your {{ i + 1 | ordinal }} photo</p>
</div>

The ordinal pipe:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'ordinal'})
export class OrdinalPipe implements PipeTransform {
    transform(int) {
        const ones = +int % 10, tens = +int % 100 - ones;
        return int + ["th","st","nd","rd"][ tens === 10 || ones > 3 ? 0 : ones ];
    }
}

@Brad's answer and comment gives the critical information about the *ngFor index. This answer expands on that, providing a pipe to transform a number (specifically, one more than the index) into the appropriate ordinal-suffix-containing-string, e.g. converting 2 to "2nd". Note that i is incremented before the pipe because index is 0-based while ordinals are 1-based.

like image 149
Andrew Willems Avatar answered Nov 11 '22 11:11

Andrew Willems


*ngFor has an index variable that you can access in the loop as explained in the documentation https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html

<div *ngFor="let item of items; let i = index;">
  <p>Pick your {{ i + 1 }} photo</p>
</div>

From this you should be able to figure out how to display 1st, 2nd, 3rd etc.

like image 23
Brad Avatar answered Nov 11 '22 12:11

Brad