Skip to content

Commit 1319c0a

Browse files
authored
fix(autocomplete): don't close when clicking inside custom origin (#19784)
We allow the consumer to set an alternate element that an autocomplete will be attached to, but our logic for closing when the user clicks outside the autocomplete didn't account for it which meant that it was being treated as not being part of the autocomplete. Fixes #19771.
1 parent 0265c2f commit 1319c0a

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/material/autocomplete/autocomplete-trigger.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -360,9 +360,11 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, AfterViewIn
360360
(this._isInsideShadowRoot && event.composedPath ? event.composedPath()[0] :
361361
event.target) as HTMLElement;
362362
const formField = this._formField ? this._formField._elementRef.nativeElement : null;
363+
const customOrigin = this.connectedTo ? this.connectedTo.elementRef.nativeElement : null;
363364

364365
return this._overlayAttached && clickTarget !== this._element.nativeElement &&
365366
(!formField || !formField.contains(clickTarget)) &&
367+
(!customOrigin || !customOrigin.contains(clickTarget)) &&
366368
(!!this._overlayRef && !this._overlayRef.overlayElement.contains(clickTarget));
367369
}));
368370
}
@@ -722,7 +724,7 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, AfterViewIn
722724
positionStrategy.withPositions(positions);
723725
}
724726

725-
private _getConnectedElement(): ElementRef {
727+
private _getConnectedElement(): ElementRef<HTMLElement> {
726728
if (this.connectedTo) {
727729
return this.connectedTo.elementRef;
728730
}

src/material/autocomplete/autocomplete.spec.ts

+19
Original file line numberDiff line numberDiff line change
@@ -2593,6 +2593,25 @@ describe('MatAutocomplete', () => {
25932593

25942594
expect(formControl.value).toBe('Cal', 'Expected new value to be propagated to model');
25952595
}));
2596+
2597+
it('should not close when clicking inside alternate origin', () => {
2598+
const fixture = createComponent(AutocompleteWithDifferentOrigin);
2599+
fixture.detectChanges();
2600+
fixture.componentInstance.connectedTo = fixture.componentInstance.alternateOrigin;
2601+
fixture.detectChanges();
2602+
fixture.componentInstance.trigger.openPanel();
2603+
fixture.detectChanges();
2604+
zone.simulateZoneExit();
2605+
2606+
expect(fixture.componentInstance.trigger.panelOpen).toBe(true);
2607+
2608+
const origin = fixture.nativeElement.querySelector('.origin');
2609+
origin.click();
2610+
fixture.detectChanges();
2611+
2612+
expect(fixture.componentInstance.trigger.panelOpen).toBe(true);
2613+
});
2614+
25962615
});
25972616

25982617
const SIMPLE_AUTOCOMPLETE_TEMPLATE = `

0 commit comments

Comments
 (0)