Skip to content

Commit d5d468a

Browse files
authored
fix(material/autocomplete): clear previous selection on reactive form reset (#27653)
prior to this commit the previous selection on reactive form field wasn't getting unselected on programmatically reset of field fixes #27652
1 parent 70b365b commit d5d468a

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/material/autocomplete/autocomplete-trigger.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -652,6 +652,12 @@ export class MatAutocompleteTrigger
652652
}
653653

654654
private _updateNativeInputValue(value: string): void {
655+
// We want to clear the previous selection if our new value is falsy. e.g: reactive form field
656+
// being reset.
657+
if (!value) {
658+
this._clearPreviousSelectedOption(null, false);
659+
}
660+
655661
// If it's used within a `MatFormField`, we should set it through the property so it can go
656662
// through change detection.
657663
if (this._formField) {

src/material/autocomplete/autocomplete.spec.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -847,6 +847,33 @@ describe('MDC-based MatAutocomplete', () => {
847847
expect(input.value).withContext(`Expected input value to be empty after reset.`).toEqual('');
848848
}));
849849

850+
it('should clear the previous selection when reactive form field is reset programmatically', fakeAsync(() => {
851+
fixture.componentInstance.trigger.openPanel();
852+
fixture.detectChanges();
853+
zone.simulateZoneExit();
854+
855+
const options = overlayContainerElement.querySelectorAll(
856+
'mat-option',
857+
) as NodeListOf<HTMLElement>;
858+
const clickedOption = options[0];
859+
const option = fixture.componentInstance.options.first;
860+
861+
clickedOption.click();
862+
fixture.detectChanges();
863+
864+
expect(fixture.componentInstance.stateCtrl.value).toEqual({code: 'AL', name: 'Alabama'});
865+
expect(option.selected).toBe(true);
866+
867+
fixture.componentInstance.stateCtrl.reset();
868+
tick();
869+
870+
fixture.detectChanges();
871+
tick();
872+
873+
expect(fixture.componentInstance.stateCtrl.value).toEqual(null);
874+
expect(option.selected).toBe(false);
875+
}));
876+
850877
it('should disable input in view when disabled programmatically', () => {
851878
const formFieldElement = fixture.debugElement.query(
852879
By.css('.mat-mdc-form-field'),

0 commit comments

Comments
 (0)