Skip to content

Commit a115b3a

Browse files
crisbetojelbourn
authored andcommitted
fix(select): error when navigating via keyboard to reset option on a closed select (#15160)
Fixes `mat-select` throwing an error when the user reaches a reset option using the arrow keys on a closed select. Seems to be due to a missing null check in the changes from #14540. Fixes #15159.
1 parent b67837f commit a115b3a

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

src/lib/select/select.spec.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,21 @@ describe('MatSelect', () => {
383383
flush();
384384
})));
385385

386+
it('should not throw when reaching a reset option using the arrow keys on a closed select',
387+
fakeAsync(() => {
388+
fixture.componentInstance.foods =
389+
[{value: 'steak-0', viewValue: 'Steak'}, {value: null, viewValue: 'None'}];
390+
fixture.detectChanges();
391+
fixture.componentInstance.control.setValue('steak-0');
392+
393+
expect(() => {
394+
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
395+
fixture.detectChanges();
396+
}).not.toThrow();
397+
398+
flush();
399+
}));
400+
386401
it('should open a single-selection select using ALT + DOWN_ARROW', fakeAsync(() => {
387402
const {control: formControl, select: selectInstance} = fixture.componentInstance;
388403

src/lib/select/select.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -714,7 +714,7 @@ export class MatSelect extends _MatSelectMixinBase implements AfterContentInit,
714714
event.preventDefault(); // prevents the page from scrolling down when pressing space
715715
this.open();
716716
} else if (!this.multiple) {
717-
const selectedOption = this.selected;
717+
const previouslySelectedOption = this.selected;
718718

719719
if (keyCode === HOME || keyCode === END) {
720720
keyCode === HOME ? manager.setFirstItemActive() : manager.setLastItemActive();
@@ -723,10 +723,12 @@ export class MatSelect extends _MatSelectMixinBase implements AfterContentInit,
723723
manager.onKeydown(event);
724724
}
725725

726+
const selectedOption = this.selected;
727+
726728
// Since the value has changed, we need to announce it ourselves.
727729
// @breaking-change 8.0.0 remove null check for _liveAnnouncer.
728-
if (this._liveAnnouncer && selectedOption !== this.selected) {
729-
this._liveAnnouncer.announce((this.selected as MatOption).viewValue);
730+
if (this._liveAnnouncer && selectedOption && previouslySelectedOption !== selectedOption) {
731+
this._liveAnnouncer.announce((selectedOption as MatOption).viewValue);
730732
}
731733
}
732734
}

0 commit comments

Comments
 (0)