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

Angular Material selectionChange返回上一步而非当前步问题

解决mat-vertical-stepper selectionChange事件获取当前步骤索引的问题

你碰到的这个情况我之前也遇到过,本质是对StepperSelectionEvent的属性用错啦!Angular Material的步进器selectionChange事件里,事件对象包含两个关键属性:

  • selectedIndex:当前刚选中的步骤索引(这才是你要的)
  • previouslySelectedIndex:上一步的索引(你之前拿到的应该是这个)

下面给你具体的修复步骤:

1. 修正HTML中的事件传递

确保你在模板里正确把事件对象传给处理方法,用$event作为参数:

<div class="row">
  <div class="col-7 stepperColumn">
    <mat-vertical-stepper (selectionChange)="onStepChange($event)">
      <!-- 你的步骤内容 -->
    </mat-vertical-stepper>
  </div>
  <div class="col-5">
    <!-- 描述展示区域 -->
  </div>
</div>

2. 在组件类中正确处理事件

首先导入StepperSelectionEvent,然后在方法里取selectedIndex:

import { Component } from '@angular/core';
import { StepperSelectionEvent } from '@angular/material/stepper';

@Component({
  // 组件元数据(比如selector、templateUrl等)
})
export class YourComponent {
  // 假设你有一个存储各步骤描述的数组
  stepDescriptions = [
    "第一步:填写用户基本信息",
    "第二步:配置服务参数",
    "第三步:确认并提交"
  ];
  currentDescription = this.stepDescriptions[0];

  onStepChange(event: StepperSelectionEvent) {
    // 这里用event.selectedIndex拿到当前选中的步骤索引
    const currentIndex = event.selectedIndex;
    this.currentDescription = this.stepDescriptions[currentIndex];
    console.log('当前选中步骤:', currentIndex);
  }
}

为什么之前拿到的是上一步索引?

很大概率是你在方法里误用到了event.previouslySelectedIndex,或者模板里没有正确传递$event(比如用了自定义的变量名但没对应上),导致拿到的是旧的索引值。

完整示例

把描述区域和步进器结合起来,就能实现选中步骤时自动更新描述:

<div class="row">
  <div class="col-7 stepperColumn">
    <mat-vertical-stepper (selectionChange)="onStepChange($event)">
      <mat-step label="基本信息">
        <p>这里是第一步的表单内容</p>
      </mat-step>
      <mat-step label="服务配置">
        <p>这里是第二步的配置选项</p>
      </mat-step>
      <mat-step label="确认提交">
        <p>这里是第三步的确认内容</p>
      </mat-step>
    </mat-vertical-stepper>
  </div>
  <div class="col-5">
    <h4>步骤说明</h4>
    <p class="description-text">{{ currentDescription }}</p>
  </div>
</div>

这样调整后,就能精准获取当前选中的步骤索引,实时更新右侧的描述内容啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:32:21