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
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.
*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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With