Skip to content

Commit 0fcdae4

Browse files
crisbetojelbourn
authored andcommitted
fix(stepper): handle removing a step before the current one (#11813)
Fixes an error that is thrown by the stepper if a step before the current one is removed. Fixes #11791.
1 parent 6bb0ffe commit 0fcdae4

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/cdk/stepper/stepper.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,12 @@ export class CdkStepper implements AfterViewInit, OnDestroy {
244244
.subscribe(direction => this._keyManager.withHorizontalOrientation(direction));
245245

246246
this._keyManager.updateActiveItemIndex(this._selectedIndex);
247+
248+
this._steps.changes.pipe(takeUntil(this._destroyed)).subscribe(() => {
249+
if (!this.selected) {
250+
this._selectedIndex = Math.max(this._selectedIndex - 1, 0);
251+
}
252+
});
247253
}
248254

249255
ngOnDestroy() {

src/lib/stepper/stepper.spec.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,24 @@ describe('MatStepper', () => {
388388
expect(headers.every(header => header.getAttribute('aria-setsize') === '3')).toBe(true);
389389
});
390390

391+
it('should adjust the index when removing a step before the current one', () => {
392+
const stepperComponent: MatVerticalStepper = fixture.debugElement
393+
.query(By.css('mat-vertical-stepper')).componentInstance;
394+
395+
stepperComponent.selectedIndex = 2;
396+
fixture.detectChanges();
397+
398+
// Re-assert since the setter has some extra logic.
399+
expect(stepperComponent.selectedIndex).toBe(2);
400+
401+
expect(() => {
402+
fixture.componentInstance.showStepTwo = false;
403+
fixture.detectChanges();
404+
}).not.toThrow();
405+
406+
expect(stepperComponent.selectedIndex).toBe(1);
407+
});
408+
391409
});
392410

393411
describe('icon overrides', () => {
@@ -1038,7 +1056,7 @@ class SimpleMatHorizontalStepperApp {
10381056
<button mat-button matStepperNext>Next</button>
10391057
</div>
10401058
</mat-step>
1041-
<mat-step>
1059+
<mat-step *ngIf="showStepTwo">
10421060
<ng-template matStepLabel>Step 2</ng-template>
10431061
Content 2
10441062
<div>
@@ -1058,6 +1076,7 @@ class SimpleMatHorizontalStepperApp {
10581076
})
10591077
class SimpleMatVerticalStepperApp {
10601078
inputLabel = 'Step 3';
1079+
showStepTwo = true;
10611080
}
10621081

10631082
@Component({

0 commit comments

Comments
 (0)