bbop99
bbop99

Reputation: 1685

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

Upvotes: 4

Views: 2775

Answers (1)

Fabian Beyerlein
Fabian Beyerlein

Reputation: 807

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

Upvotes: 2

Related Questions