Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(cdk/a11y): ensure that aria describer ID is unique #24982

Merged
merged 1 commit into from
May 30, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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++}`;
}
}