From f54377c41663495d18a2acdd685efe331eefccf3 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Fri, 26 Jan 2018 16:36:13 +0100 Subject: [PATCH] fix(stepper): throw when out-of-bounds value is assigned to selectedIndex (#9127) Throws better error when an out-of-bounds value is assigned to the `selectedIndex`. --- src/cdk/stepper/stepper.ts | 7 ++++++- src/lib/stepper/stepper.spec.ts | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/cdk/stepper/stepper.ts b/src/cdk/stepper/stepper.ts index c2fa1bfc385..53e719a0b3c 100644 --- a/src/cdk/stepper/stepper.ts +++ b/src/cdk/stepper/stepper.ts @@ -165,6 +165,11 @@ export class CdkStepper implements OnDestroy { get selectedIndex() { return this._selectedIndex; } set selectedIndex(index: number) { if (this._steps) { + // Ensure that the index can't be out of bounds. + if (index < 0 || index > this._steps.length - 1) { + throw Error('cdkStepper: Cannot assign out-of-bounds value to `selectedIndex`.'); + } + if (this._anyControlsInvalidOrPending(index) || index < this._selectedIndex && !this._steps.toArray()[index].editable) { // remove focus from clicked step header if the step is not able to be selected @@ -177,7 +182,7 @@ export class CdkStepper implements OnDestroy { this._selectedIndex = this._focusIndex = index; } } - private _selectedIndex: number = 0; + private _selectedIndex = 0; /** The step that is selected. */ @Input() diff --git a/src/lib/stepper/stepper.spec.ts b/src/lib/stepper/stepper.spec.ts index 7634861e84f..a4c34e1691c 100644 --- a/src/lib/stepper/stepper.spec.ts +++ b/src/lib/stepper/stepper.spec.ts @@ -54,6 +54,26 @@ describe('MatHorizontalStepper', () => { expect(stepperComponent.selectedIndex).toBe(0); }); + it('should throw when a negative `selectedIndex` is assigned', () => { + const stepperComponent: MatHorizontalStepper = fixture.debugElement + .query(By.css('mat-horizontal-stepper')).componentInstance; + + expect(() => { + stepperComponent.selectedIndex = -10; + fixture.detectChanges(); + }).toThrowError(/Cannot assign out-of-bounds/); + }); + + it('should throw when an out-of-bounds `selectedIndex` is assigned', () => { + const stepperComponent: MatHorizontalStepper = fixture.debugElement + .query(By.css('mat-horizontal-stepper')).componentInstance; + + expect(() => { + stepperComponent.selectedIndex = 1337; + fixture.detectChanges(); + }).toThrowError(/Cannot assign out-of-bounds/); + }); + it('should change selected index on header click', () => { let stepHeaders = fixture.debugElement.queryAll(By.css('.mat-horizontal-stepper-header')); assertSelectionChangeOnHeaderClick(fixture, stepHeaders);