You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中基于条件递减ngFor循环索引 实现特殊发票序号始终从1开始

Angular 特殊发票序号固定从1开始的实现方案

有两种常用实现方案,可根据业务复杂度选择:


方案1:模板结合组件属性计算(适配保留原遍历顺序的场景)

先在组件内统计普通发票的总数量,模板渲染特殊发票时用总索引减去普通发票数量即可修正序号:

组件类代码

// 新增属性存储普通发票数量
generalInvoiceCount: number = 0;

// 拿到发票数组后统计数量
ngOnInit() {
  this.generalInvoiceCount = this.invoices.filter(invoice => 
    invoice.name.startsWith('general')
  ).length;
}

模板代码

<div class="list-group list-group-flush" *ngFor="let invoice of invoices;index as i">
  <a *ngIf="invoice.name.startsWith('general')" class="list-group-item list-group-item-action" [href]="invoice.url" download>General Invoice</a>
  <a *ngIf="invoice.name.startsWith('special')" class="list-group-item list-group-item-action" [href]="invoice.url" download> Special Invoice number {{i - generalInvoiceCount + 1}}</a>
</div>

方案2:拆分数组分开遍历(更推荐,逻辑更清晰)

直接在组件内把发票拆成普通、特殊两个独立数组,分开遍历,特殊发票的序号直接用自身遍历的索引生成,完全不受普通发票影响:

组件类代码

// 拆分两个独立的发票数组
generalInvoices: any[] = [];
specialInvoices: any[] = [];

// 拿到原始发票数组后拆分
ngOnInit() {
  this.invoices.forEach(invoice => {
    if(invoice.name.startsWith('general')) {
      this.generalInvoices.push(invoice);
    } else if(invoice.name.startsWith('special')) {
      this.specialInvoices.push(invoice);
    }
  })
}

模板代码

<div class="list-group list-group-flush">
  <!-- 遍历普通发票 -->
  <a *ngFor="let invoice of generalInvoices" class="list-group-item list-group-item-action" [href]="invoice.url" download>General Invoice</a>
  <!-- 遍历特殊发票,用自身的遍历索引生成序号 -->
  <a *ngFor="let invoice of specialInvoices; index as i" class="list-group-item list-group-item-action" [href]="invoice.url" download> Special Invoice number {{i + 1}}</a>
</div>

内容的提问来源于stack exchange,提问作者Sagar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 23:45:02