diff --git a/src/cdk/stepper/stepper.ts b/src/cdk/stepper/stepper.ts index e7a3f643cba9..9b07794d81a5 100644 --- a/src/cdk/stepper/stepper.ts +++ b/src/cdk/stepper/stepper.ts @@ -8,7 +8,7 @@ import {FocusableOption, FocusKeyManager} from '@angular/cdk/a11y'; import {Direction, Directionality} from '@angular/cdk/bidi'; -import {coerceBooleanProperty} from '@angular/cdk/coercion'; +import {coerceBooleanProperty, coerceNumberProperty} from '@angular/cdk/coercion'; import {END, ENTER, HOME, SPACE, hasModifierKey} from '@angular/cdk/keycodes'; import { AfterViewInit, @@ -276,19 +276,21 @@ export class CdkStepper implements AfterViewInit, OnDestroy { @Input() get selectedIndex() { return this._selectedIndex; } set selectedIndex(index: number) { + const newIndex = coerceNumberProperty(index); + if (this.steps) { // Ensure that the index can't be out of bounds. - if (index < 0 || index > this.steps.length - 1) { + if (newIndex < 0 || newIndex > this.steps.length - 1) { throw Error('cdkStepper: Cannot assign out-of-bounds value to `selectedIndex`.'); } - if (this._selectedIndex != index && - !this._anyControlsInvalidOrPending(index) && - (index >= this._selectedIndex || this.steps.toArray()[index].editable)) { + if (this._selectedIndex != newIndex && + !this._anyControlsInvalidOrPending(newIndex) && + (newIndex >= this._selectedIndex || this.steps.toArray()[newIndex].editable)) { this._updateSelectedItemIndex(index); } } else { - this._selectedIndex = index; + this._selectedIndex = newIndex; } } private _selectedIndex = 0; diff --git a/src/lib/stepper/stepper.spec.ts b/src/lib/stepper/stepper.spec.ts index 09ba88592217..e25f3f8a1e67 100644 --- a/src/lib/stepper/stepper.spec.ts +++ b/src/lib/stepper/stepper.spec.ts @@ -705,13 +705,26 @@ describe('MatStepper', () => { describe('linear stepper with a pre-defined selectedIndex', () => { let preselectedFixture: ComponentFixture; + let stepper: MatHorizontalStepper; + beforeEach(() => { preselectedFixture = createComponent(SimplePreselectedMatHorizontalStepperApp); + preselectedFixture.detectChanges(); + stepper = preselectedFixture.debugElement + .query(By.directive(MatHorizontalStepper)).componentInstance; }); it('should not throw', () => { expect(() => preselectedFixture.detectChanges()).not.toThrow(); }); + + it('selectedIndex should be typeof number', () => { + expect(typeof stepper.selectedIndex).toBe('number'); + }); + + it('value of selectedIndex should be the pre-defined value', () => { + expect(stepper.selectedIndex).toBe(0); + }); }); describe('linear stepper with no `stepControl`', () => {