Skip to content

Commit 797366a

Browse files
committed
fix(stepper): handle out-of-bounds value being assigned to the selectedIndex
Fixes the stepper throwing an error if the consumer sets a `selectedIndex` that is greater than the amount of steps or less than zero.
1 parent c3d7cd9 commit 797366a

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/cdk/stepper/stepper.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,9 @@ export class CdkStepper implements OnDestroy {
152152
get selectedIndex() { return this._selectedIndex; }
153153
set selectedIndex(index: number) {
154154
if (this._steps) {
155+
// Ensure that the index can't be out of bounds.
156+
index = Math.max(0, Math.min(this._steps.length - 1, index || 0));
157+
155158
if (this._anyControlsInvalidOrPending(index) || index < this._selectedIndex &&
156159
!this._steps.toArray()[index].editable) {
157160
// remove focus from clicked step header if the step is not able to be selected
@@ -164,7 +167,7 @@ export class CdkStepper implements OnDestroy {
164167
this._selectedIndex = this._focusIndex = index;
165168
}
166169
}
167-
private _selectedIndex: number = 0;
170+
private _selectedIndex = 0;
168171

169172
/** The step that is selected. */
170173
@Input()

src/lib/stepper/stepper.spec.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,30 @@ describe('MatHorizontalStepper', () => {
5151
expect(stepperComponent.selectedIndex).toBe(0);
5252
});
5353

54+
it('should not throw when a negative `selectedIndex` is assigned', () => {
55+
const stepperComponent: MatHorizontalStepper = fixture.debugElement
56+
.query(By.css('mat-horizontal-stepper')).componentInstance;
57+
58+
expect(() => {
59+
stepperComponent.selectedIndex = -10;
60+
fixture.detectChanges();
61+
}).not.toThrow();
62+
63+
expect(stepperComponent.selectedIndex).toBe(0);
64+
});
65+
66+
it('should not throw when an out-of-bounds `selectedIndex` is assigned', () => {
67+
const stepperComponent: MatHorizontalStepper = fixture.debugElement
68+
.query(By.css('mat-horizontal-stepper')).componentInstance;
69+
70+
expect(() => {
71+
stepperComponent.selectedIndex = 1337;
72+
fixture.detectChanges();
73+
}).not.toThrow();
74+
75+
expect(stepperComponent.selectedIndex).toBe(2);
76+
});
77+
5478
it('should change selected index on header click', () => {
5579
let stepHeaders = fixture.debugElement.queryAll(By.css('.mat-horizontal-stepper-header'));
5680
assertSelectionChangeOnHeaderClick(fixture, stepHeaders);

0 commit comments

Comments
 (0)