diff --git a/src/material/autocomplete/autocomplete-trigger.ts b/src/material/autocomplete/autocomplete-trigger.ts index a0d6608993d4..6c36e91d8665 100644 --- a/src/material/autocomplete/autocomplete-trigger.ts +++ b/src/material/autocomplete/autocomplete-trigger.ts @@ -284,6 +284,11 @@ export class MatAutocompleteTrigger 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. */ @@ -323,6 +328,12 @@ export class MatAutocompleteTrigger // 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 27365fa5b76f..3eec12470f53 100644 --- a/src/material/autocomplete/autocomplete.spec.ts +++ b/src/material/autocomplete/autocomplete.spec.ts @@ -3698,6 +3698,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); + })); }); });