From 4638833d02edf5776b257c318209616b25527df0 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Tue, 8 May 2018 18:53:26 +0200 Subject: [PATCH] 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. --- src/cdk/stepper/stepper.ts | 7 +++++-- src/lib/stepper/stepper.spec.ts | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/cdk/stepper/stepper.ts b/src/cdk/stepper/stepper.ts index b09d4a87e5c..0c4ada77f92 100644 --- a/src/cdk/stepper/stepper.ts +++ b/src/cdk/stepper/stepper.ts @@ -189,9 +189,12 @@ export class CdkStepper implements AfterViewInit, OnDestroy { /** The step that is selected. */ @Input() - get selected(): CdkStep { return this._steps.toArray()[this.selectedIndex]; } + get selected(): CdkStep { + // @deletion-target 7.0.0 Change return type to `CdkStep | undefined`. + return this._steps ? this._steps.toArray()[this.selectedIndex] : undefined!; + } set selected(step: CdkStep) { - this.selectedIndex = this._steps.toArray().indexOf(step); + this.selectedIndex = this._steps ? this._steps.toArray().indexOf(step) : -1; } /** Event emitted when the selected step has changed. */ diff --git a/src/lib/stepper/stepper.spec.ts b/src/lib/stepper/stepper.spec.ts index 8b63658ec16..72da8f0e36b 100644 --- a/src/lib/stepper/stepper.spec.ts +++ b/src/lib/stepper/stepper.spec.ts @@ -340,6 +340,28 @@ describe('MatStepper', () => { selectionChangeSubscription.unsubscribe(); animationDoneSubscription.unsubscribe(); })); + + it('should not throw when attempting to get the selected step too early', () => { + fixture.destroy(); + fixture = TestBed.createComponent(SimpleMatVerticalStepperApp); + + const stepperComponent: MatVerticalStepper = fixture.debugElement + .query(By.css('mat-vertical-stepper')).componentInstance; + + expect(() => stepperComponent.selected).not.toThrow(); + }); + + it('should not throw when attempting to set the selected step too early', () => { + fixture.destroy(); + fixture = TestBed.createComponent(SimpleMatVerticalStepperApp); + + const stepperComponent: MatVerticalStepper = fixture.debugElement + .query(By.css('mat-vertical-stepper')).componentInstance; + + expect(() => stepperComponent.selected = null!).not.toThrow(); + expect(stepperComponent.selectedIndex).toBe(-1); + }); + }); describe('icon overrides', () => {