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

如何在Angular 17中使用新@for循环跳过数组首个元素

Angular 17 @for循环从指定索引开始展示数组元素

针对数组 arr = ["str1", "str2", "str3", "str4", "str5"],要从索引1开始展示元素,有两种常用实现方式:

方式一:数组切片预处理(推荐)

利用数组的slice()方法提前截取从索引1开始的子数组,直接遍历这个子数组即可:

组件代码

import { Component } from '@angular/core';

@Component({
  selector: 'app-index-demo',
  standalone: true,
  template: `
    @for (item of arr.slice(1); track item) {
      {{ item }}
      @if (!$last) {、}
    }
  `
})
export class IndexDemoComponent {
  arr = ["str1", "str2", "str3", "str4", "str5"];
}

这种方式的优势是减少循环次数,直接遍历目标子数组,性能更优。track item是Angular 17 @for循环必须的跟踪标识,这里因为每个元素都是唯一字符串,直接用元素本身即可。

方式二:循环内判断索引

如果需要保留原数组的完整遍历逻辑,只是跳过索引0的元素,可以在循环内通过$index内置变量判断:

组件代码

import { Component } from '@angular/core';

@Component({
  selector: 'app-index-demo',
  standalone: true,
  template: `
    @for (item of arr; track $index; let idx = $index) {
      @if (idx > 0) {
        {{ item }}
        @if (!$last) {、}
      }
    }
  `
})
export class IndexDemoComponent {
  arr = ["str1", "str2", "str3", "str4", "str5"];
}

这里通过let idx = $index把循环的索引赋值给变量idx,然后判断idx > 0时才渲染元素。

两种方式最终都会输出:str2、str3、str4、str5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 09:42:40