Skip to content

Commit 4638833

Browse files
crisbetojelbourn
authored andcommitted
fix(stepper): error being thrown if selected step is accessed too early (#11186)
Fixes an error that is thrown if the selected step is accessed before `AfterViewInit`. Fixes #11158.
1 parent 9e9daf8 commit 4638833

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

src/cdk/stepper/stepper.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,9 +189,12 @@ export class CdkStepper implements AfterViewInit, OnDestroy {
189189

190190
/** The step that is selected. */
191191
@Input()
192-
get selected(): CdkStep { return this._steps.toArray()[this.selectedIndex]; }
192+
get selected(): CdkStep {
193+
// @deletion-target 7.0.0 Change return type to `CdkStep | undefined`.
194+
return this._steps ? this._steps.toArray()[this.selectedIndex] : undefined!;
195+
}
193196
set selected(step: CdkStep) {
194-
this.selectedIndex = this._steps.toArray().indexOf(step);
197+
this.selectedIndex = this._steps ? this._steps.toArray().indexOf(step) : -1;
195198
}
196199

197200
/** Event emitted when the selected step has changed. */

src/lib/stepper/stepper.spec.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,28 @@ describe('MatStepper', () => {
340340
selectionChangeSubscription.unsubscribe();
341341
animationDoneSubscription.unsubscribe();
342342
}));
343+
344+
it('should not throw when attempting to get the selected step too early', () => {
345+
fixture.destroy();
346+
fixture = TestBed.createComponent(SimpleMatVerticalStepperApp);
347+
348+
const stepperComponent: MatVerticalStepper = fixture.debugElement
349+
.query(By.css('mat-vertical-stepper')).componentInstance;
350+
351+
expect(() => stepperComponent.selected).not.toThrow();
352+
});
353+
354+
it('should not throw when attempting to set the selected step too early', () => {
355+
fixture.destroy();
356+
fixture = TestBed.createComponent(SimpleMatVerticalStepperApp);
357+
358+
const stepperComponent: MatVerticalStepper = fixture.debugElement
359+
.query(By.css('mat-vertical-stepper')).componentInstance;
360+
361+
expect(() => stepperComponent.selected = null!).not.toThrow();
362+
expect(stepperComponent.selectedIndex).toBe(-1);
363+
});
364+
343365
});
344366

345367
describe('icon overrides', () => {

0 commit comments

Comments
 (0)