Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(autocomplete): restore focus after emitting option selected event #18707

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions src/material/autocomplete/autocomplete-trigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -595,12 +595,14 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, AfterViewIn
* stemmed from the user.
*/
private _setValueAndClose(event: MatOptionSelectionChange | null): void {
if (event && event.source) {
this._clearPreviousSelectedOption(event.source);
this._setTriggerValue(event.source.value);
this._onChange(event.source.value);
const source = event && event.source;

if (source) {
this._clearPreviousSelectedOption(source);
this._setTriggerValue(source.value);
this._onChange(source.value);
this.autocomplete._emitSelectEvent(source);
this._element.nativeElement.focus();
this.autocomplete._emitSelectEvent(event.source);
}

this.closePanel();
Expand Down
22 changes: 22 additions & 0 deletions src/material/autocomplete/autocomplete.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2468,6 +2468,28 @@ describe('MatAutocomplete', () => {
expect(event.option.value).toBe('Washington');
}));

it('should refocus the input after the selection event is emitted', fakeAsync(() => {
const events: string[] = [];
const fixture = createComponent(AutocompleteWithSelectEvent);
fixture.detectChanges();
const input = fixture.nativeElement.querySelector('input');

fixture.componentInstance.trigger.openPanel();
zone.simulateZoneExit();
fixture.detectChanges();

const options =
overlayContainerElement.querySelectorAll('mat-option') as NodeListOf<HTMLElement>;
spyOn(input, 'focus').and.callFake(() => events.push('focus'));
fixture.componentInstance.optionSelected.and.callFake(() => events.push('select'));

options[1].click();
tick();
fixture.detectChanges();

expect(events).toEqual(['select', 'focus']);
}));

it('should emit an event when a newly-added option is selected', fakeAsync(() => {
let fixture = createComponent(AutocompleteWithSelectEvent);

Expand Down