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

Angular中如何通过ngFor实现点击切换显示相邻三个元素?

实现动态切换显示的标题列表

首先修正你代码里的两个小问题:

  • 数组title中t4和t5之间缺少逗号,应该改为["t1", "t2", "t3", "t4", "t5", "t6"]
  • 模板中遍历的是work数组,但你定义的是title,需要统一变量名

接下来按照需求实现动态切换逻辑:

组件类代码

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

@Component({
  selector: 'app-title-list',
  templateUrl: './title-list.component.html'
})
export class TitleListComponent {
  // 修正后的标题数组
  title = ["t1", "t2", "t3", "t4", "t5", "t6"];
  // 初始中间元素为t2(索引1),对应显示t1、t2、t3
  activeMiddleIndex = 1;

  // 点击标题时更新中间元素索引
  changeindex(originalIndex: number) {
    this.activeMiddleIndex = originalIndex;
  }

  // 获取当前要显示的标题列表
  get displayTitles() {
    const total = this.title.length;
    // 如果数组长度<=3,直接显示全部
    if (total <= 3) return [...this.title];

    let startIndex: number;
    // 处理边界情况:点击第一个元素时,显示前3个
    if (this.activeMiddleIndex === 0) {
      startIndex = 0;
    } 
    // 点击最后一个元素时,显示后3个
    else if (this.activeMiddleIndex === total - 1) {
      startIndex = total - 3;
    } 
    // 其他情况:显示当前元素的前一个、自身、后一个
    else {
      startIndex = this.activeMiddleIndex - 1;
    }
    // 截取3个元素返回
    return this.title.slice(startIndex, startIndex + 3);
  }

  // 获取当前显示元素对应的原数组索引
  get originalIndices() {
    const total = this.title.length;
    if (total <= 3) return Array.from({ length: total }, (_, i) => i);

    let startIndex: number;
    if (this.activeMiddleIndex === 0) {
      startIndex = 0;
    } else if (this.activeMiddleIndex === total - 1) {
      startIndex = total - 3;
    } else {
      startIndex = this.activeMiddleIndex - 1;
    }
    return [startIndex, startIndex + 1, startIndex + 2];
  }
}

模板代码

<div *ngFor="let item of displayTitles; let i = index" 
     (click)="changeindex(originalIndices[i])">
  <div>{{item}}</div>
</div>

逻辑说明

  1. 初始状态:activeMiddleIndex设为1(对应t2),所以displayTitles返回索引0-2的元素,即t1、t2、t3
  2. 点击t3(原索引2):activeMiddleIndex变为2,此时返回索引1-3的元素,即t2、t3、t4
  3. 点击t2(原索引1):activeMiddleIndex变回1,返回索引0-2的元素,恢复显示t1、t2、t3
  4. 边界处理:点击t1时始终显示前3个,点击t6时始终显示后3个,数组长度不足3时显示全部元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:45:30