Skip to content

Commit

Permalink
fix(material/autocomplete): clear previous selection on reactive form…
Browse files Browse the repository at this point in the history
… reset (#27653)

prior to this commit the previous selection on reactive form field wasn't getting unselected on programmatically reset of field

fixes #27652
  • Loading branch information
naaajii committed Nov 9, 2023
1 parent 70b365b commit d5d468a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/material/autocomplete/autocomplete-trigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,12 @@ export class MatAutocompleteTrigger
}

private _updateNativeInputValue(value: string): void {
// We want to clear the previous selection if our new value is falsy. e.g: reactive form field
// being reset.
if (!value) {
this._clearPreviousSelectedOption(null, false);
}

// If it's used within a `MatFormField`, we should set it through the property so it can go
// through change detection.
if (this._formField) {
Expand Down
27 changes: 27 additions & 0 deletions src/material/autocomplete/autocomplete.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,33 @@ describe('MDC-based MatAutocomplete', () => {
expect(input.value).withContext(`Expected input value to be empty after reset.`).toEqual('');
}));

it('should clear the previous selection when reactive form field is reset programmatically', fakeAsync(() => {
fixture.componentInstance.trigger.openPanel();
fixture.detectChanges();
zone.simulateZoneExit();

const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
const clickedOption = options[0];
const option = fixture.componentInstance.options.first;

clickedOption.click();
fixture.detectChanges();

expect(fixture.componentInstance.stateCtrl.value).toEqual({code: 'AL', name: 'Alabama'});
expect(option.selected).toBe(true);

fixture.componentInstance.stateCtrl.reset();
tick();

fixture.detectChanges();
tick();

expect(fixture.componentInstance.stateCtrl.value).toEqual(null);
expect(option.selected).toBe(false);
}));

it('should disable input in view when disabled programmatically', () => {
const formFieldElement = fixture.debugElement.query(
By.css('.mat-mdc-form-field'),
Expand Down

0 comments on commit d5d468a

Please sign in to comment.