3

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

bbop99
  • 1,625
  • 1
  • 11
  • 25
  • Possible duplicate of [angular material stepper add new step items dynamically on every click](https://stackoverflow.com/questions/54274173/angular-material-stepper-add-new-step-items-dynamically-on-every-click) – Alex Sep 18 '19 at 16:46
  • @Adam the issue you reference focuses just on adding steps dynamically which works fine - it's the navigating to it immediately afterwards which causes the exception – bbop99 Sep 18 '19 at 16:56

1 Answers1

1

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

Fabian Beyerlein
  • 767
  • 1
  • 10
  • 17