diff --git a/src/material/autocomplete/autocomplete-trigger.ts b/src/material/autocomplete/autocomplete-trigger.ts index 85e9860c7e03..b30fff280615 100644 --- a/src/material/autocomplete/autocomplete-trigger.ts +++ b/src/material/autocomplete/autocomplete-trigger.ts @@ -263,6 +263,11 @@ export abstract class _MatAutocompleteTriggerBase openPanel(): void { this._attachOverlay(); this._floatLabel(); + // Add aria-owns attribute when the autocomplete becomes visible. + if (this._trackedModal) { + const panelId = this.autocomplete.id; + addAriaReferencedId(this._trackedModal, 'aria-owns', panelId); + } } /** Closes the autocomplete suggestion panel. */ @@ -302,6 +307,12 @@ export abstract class _MatAutocompleteTriggerBase // user clicks outside. this._changeDetectorRef.detectChanges(); } + + // Remove aria-owns attribute when the autocomplete is no longer visible. + if (this._trackedModal) { + const panelId = this.autocomplete.id; + removeAriaReferencedId(this._trackedModal, 'aria-owns', panelId); + } } /** diff --git a/src/material/autocomplete/autocomplete.spec.ts b/src/material/autocomplete/autocomplete.spec.ts index 41e51dd5a3d7..4ec0c3470218 100644 --- a/src/material/autocomplete/autocomplete.spec.ts +++ b/src/material/autocomplete/autocomplete.spec.ts @@ -3729,6 +3729,31 @@ describe('MDC-based MatAutocomplete', () => { .withContext('expecting modal to own the autocommplete panel') .toContain(panelId); })); + + it('should remove the aria-owns attribute of the modal when the autocomplete panel closes', fakeAsync(() => { + fixture.componentInstance.trigger.openPanel(); + fixture.componentInstance.trigger.closePanel(); + fixture.detectChanges(); + + const panelId = fixture.componentInstance.autocomplete.id; + const modalElement = fixture.componentInstance.modal.nativeElement; + + expect(modalElement.getAttribute('aria-owns')).toBeFalsy(); + })); + + it('should readd the aria-owns attribute of the modal when the autocomplete panel opens again', fakeAsync(() => { + fixture.componentInstance.trigger.openPanel(); + fixture.componentInstance.trigger.closePanel(); + fixture.componentInstance.trigger.openPanel(); + fixture.detectChanges(); + + const panelId = fixture.componentInstance.autocomplete.id; + const modalElement = fixture.componentInstance.modal.nativeElement; + + expect(modalElement.getAttribute('aria-owns')?.split(' ')) + .withContext('expecting modal to own the autocommplete panel') + .toContain(panelId); + })); }); });