diff --git a/src/cdk/stepper/stepper.ts b/src/cdk/stepper/stepper.ts index 3d9a3f429055..3144d80b7632 100644 --- a/src/cdk/stepper/stepper.ts +++ b/src/cdk/stepper/stepper.ts @@ -155,6 +155,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 @@ -167,7 +172,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 5dd85b3bc260..342c155dcdda 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);