gpt4 book ai didi

Angular 2 - 当您想显示 "1st"、 "2nd"、 "3rd"等时如何处理 *ngFor ?

转载 作者:行者123 更新时间:2023-12-03 23:41:24 24 4
gpt4 key购买 nike

我正在尝试创建一个循环来显示一些 div,介于 1 和 7 之间。

但是,每个 div 都会有一个 <p> Pick your 1st photo </p> ,其中第一项会说 1st ,第二项 2nd ,第三项 3rd 等。

我该如何处理这样的事情?

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

谢谢

最佳答案

index 中使用 *ngFor,然后使用 ordinal 管道转换比索引多一:

<div *ngFor="let item of items; let i = index">
<p>Pick your {{ i + 1 | ordinal }} photo</p>
</div>
ordinal 管道:
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 和 comment 给出了关于 *ngFor index 的关键信息。这个答案对此进行了扩展,提供了一个管道来将数字(特别是比索引多一个)转换为适当的序数后缀包含字符串,例如将 2 转换为 "2nd" 。请注意, i 在管道之前递增,因为 index 从 0 开始,而序数从 1 开始。

关于Angular 2 - 当您想显示 "1st"、 "2nd"、 "3rd"等时如何处理 *ngFor ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39480498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com