Skip to content

Commit f54377c

Browse files
crisbetojelbourn
authored andcommitted
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`.
1 parent 1038950 commit f54377c

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
@@ -165,6 +165,11 @@ export class CdkStepper implements OnDestroy {
165165
get selectedIndex() { return this._selectedIndex; }
166166
set selectedIndex(index: number) {
167167
if (this._steps) {
168+
// Ensure that the index can't be out of bounds.
169+
if (index < 0 || index > this._steps.length - 1) {
170+
throw Error('cdkStepper: Cannot assign out-of-bounds value to `selectedIndex`.');
171+
}
172+
168173
if (this._anyControlsInvalidOrPending(index) || index < this._selectedIndex &&
169174
!this._steps.toArray()[index].editable) {
170175
// remove focus from clicked step header if the step is not able to be selected
@@ -177,7 +182,7 @@ export class CdkStepper implements OnDestroy {
177182
this._selectedIndex = this._focusIndex = index;
178183
}
179184
}
180-
private _selectedIndex: number = 0;
185+
private _selectedIndex = 0;
181186

182187
/** The step that is selected. */
183188
@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)