Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding step to mat-stepper and navigating to it throws out of bounds error

I am working with a simple mat-stepper where steps are generated from an array using *ngFor.

I'd like to dynamically add a step to the display after the stepper has been rendered and then immediately navigate to it programmatically.

Adding the steps dynamically works fine - the navigating part is the issue as it leads to an exception: "Error: cdkStepper: Cannot assign out-of-bounds value to selectedIndex" even though the assigned index should be in bounds based on the steps having been passed to the components.

Simplified example to illustrate the issue (the timeout is just a placeholder for async behaviour that leads to the addition of extra steps).

steps = ['step1', 'step2'];
selectedIndex = 1;

ngOnInit() {
  setTimeout(() => {
    this.steps.push('step3');
    this.selectedIndex = 2;
  });
}

<mat-stepper [selectedIndex]="selectedIndex">
  <mat-step *ngFor="let step of steps">
    {{step}}
  </mat-step>
</mat-stepper>

Any ideas on how we might get around this?

Full Example: https://stackblitz.com/edit/angular-cdafd9?file=app%2Fstepper-overview-example.ts

like image 537
Anton v B Avatar asked Oct 23 '25 18:10

Anton v B


1 Answers

It seems like the stepper needs a bit to initialize. If you add the step before setTimeout it works just fine.

like image 98
Fabian Beyerlein Avatar answered Oct 26 '25 08:10

Fabian Beyerlein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!