Skip to content

Commit ef9c8f4

Browse files
committed
fix(stepper): throw when out-of-bounds value is assigned to selectedIndex
Throws better error when an out-of-bounds value is assigned to the `selectedIndex`.
1 parent 4523556 commit ef9c8f4

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 & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,11 @@ export class CdkStepper implements OnDestroy {
155155
get selectedIndex() { return this._selectedIndex; }
156156
set selectedIndex(index: number) {
157157
if (this._steps) {
158+
// Ensure that the index can't be out of bounds.
159+
if (index < 0 || index > this._steps.length - 1) {
160+
throw Error('cdkStepper: Cannot assign out-of-bounds value to `selectedIndex`.');
161+
}
162+
158163
if (this._anyControlsInvalidOrPending(index) || index < this._selectedIndex &&
159164
!this._steps.toArray()[index].editable) {
160165
// remove focus from clicked step header if the step is not able to be selected
@@ -167,7 +172,7 @@ export class CdkStepper implements OnDestroy {
167172
this._selectedIndex = this._focusIndex = index;
168173
}
169174
}
170-
private _selectedIndex: number = 0;
175+
private _selectedIndex = 0;
171176

172177
/** The step that is selected. */
173178
@Input()

src/lib/stepper/stepper.spec.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,26 @@ describe('MatHorizontalStepper', () => {
5454
expect(stepperComponent.selectedIndex).toBe(0);
5555
});
5656

57+
it('should throw when a negative `selectedIndex` is assigned', () => {
58+
const stepperComponent: MatHorizontalStepper = fixture.debugElement
59+
.query(By.css('mat-horizontal-stepper')).componentInstance;
60+
61+
expect(() => {
62+
stepperComponent.selectedIndex = -10;
63+
fixture.detectChanges();
64+
}).toThrowError(/Cannot assign out-of-bounds/);
65+
});
66+
67+
it('should throw when an out-of-bounds `selectedIndex` is assigned', () => {
68+
const stepperComponent: MatHorizontalStepper = fixture.debugElement
69+
.query(By.css('mat-horizontal-stepper')).componentInstance;
70+
71+
expect(() => {
72+
stepperComponent.selectedIndex = 1337;
73+
fixture.detectChanges();
74+
}).toThrowError(/Cannot assign out-of-bounds/);
75+
});
76+
5777
it('should change selected index on header click', () => {
5878
let stepHeaders = fixture.debugElement.queryAll(By.css('.mat-horizontal-stepper-header'));
5979
assertSelectionChangeOnHeaderClick(fixture, stepHeaders);

0 commit comments

Comments
 (0)