Skip to content

Commit

Permalink
fix(cdk/a11y): ensure that aria describer ID is unique (#24982)
Browse files Browse the repository at this point in the history
Adds the unique application ID to the ARIA describer ID so that it's unique even if Angular is loaded multiple times.

Fixes #24917.

(cherry picked from commit b1ed1c5)
  • Loading branch information
crisbeto committed May 30, 2022
1 parent 2c5b158 commit 4edfaed
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/cdk/a11y/aria-describer/aria-describer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/

import {DOCUMENT} from '@angular/common';
import {Inject, Injectable, OnDestroy} from '@angular/core';
import {Inject, Injectable, OnDestroy, APP_ID, inject} from '@angular/core';
import {Platform} from '@angular/cdk/platform';
import {addAriaReferencedId, getAriaReferenceIds, removeAriaReferencedId} from './aria-reference';

Expand Down Expand Up @@ -74,6 +74,7 @@ export class AriaDescriber implements OnDestroy {
private _platform?: Platform,
) {
this._document = _document;
this._id = inject(APP_ID) + '-' + nextId++;
}

/**
Expand All @@ -97,7 +98,7 @@ export class AriaDescriber implements OnDestroy {

if (typeof message !== 'string') {
// We need to ensure that the element has an ID.
setMessageId(message);
setMessageId(message, this._id);
this._messageRegistry.set(key, {messageElement: message, referenceCount: 0});
} else if (!this._messageRegistry.has(key)) {
this._createMessageElement(message, role);
Expand Down Expand Up @@ -162,7 +163,7 @@ export class AriaDescriber implements OnDestroy {
*/
private _createMessageElement(message: string, role?: string) {
const messageElement = this._document.createElement('div');
setMessageId(messageElement);
setMessageId(messageElement, this._id);
messageElement.textContent = message;

if (role) {
Expand Down Expand Up @@ -297,8 +298,8 @@ function getKey(message: string | Element, role?: string): string | Element {
}

/** Assigns a unique ID to an element, if it doesn't have one already. */
function setMessageId(element: HTMLElement) {
function setMessageId(element: HTMLElement, serviceId: string) {
if (!element.id) {
element.id = `${CDK_DESCRIBEDBY_ID_PREFIX}-${nextId++}`;
element.id = `${CDK_DESCRIBEDBY_ID_PREFIX}-${serviceId}-${nextId++}`;
}
}

0 comments on commit 4edfaed

Please sign in to comment.