Skip to content
Merged
Show file tree
Hide file tree
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
18 changes: 16 additions & 2 deletions src/material/form-field/form-field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import {AbstractControlDirective} from '@angular/forms';
import {ThemePalette} from '@angular/material/core';
import {_IdGenerator} from '@angular/cdk/a11y';
import {Subject, Subscription, merge} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {map, pairwise, takeUntil, filter, startWith} from 'rxjs/operators';
import {MAT_ERROR, MatError} from './directives/error';
import {
FLOATING_LABEL_PARENT,
Expand Down Expand Up @@ -328,6 +328,7 @@ export class MatFormField
private _previousControl: MatFormFieldControl<unknown> | null = null;
private _stateChanges: Subscription | undefined;
private _valueChanges: Subscription | undefined;
private _describedByChanges: Subscription | undefined;

private _injector = inject(Injector);

Expand Down Expand Up @@ -377,6 +378,7 @@ export class MatFormField
ngOnDestroy() {
this._stateChanges?.unsubscribe();
this._valueChanges?.unsubscribe();
this._describedByChanges?.unsubscribe();
this._destroyed.next();
this._destroyed.complete();
}
Expand Down Expand Up @@ -426,10 +428,22 @@ export class MatFormField
this._stateChanges?.unsubscribe();
this._stateChanges = control.stateChanges.subscribe(() => {
this._updateFocusState();
this._syncDescribedByIds();
this._changeDetectorRef.markForCheck();
});

// Updating the `aria-describedby` touches the DOM. Only do it if it actually needs to change.
this._describedByChanges?.unsubscribe();
this._describedByChanges = control.stateChanges
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried basing this on top of signals, but the timing was off because I had to run _syncDescribedByIds in an effect.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally we'll do a bigger refactor at some point and replace syncDescribedByIds with a signal, describedByIds

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, I'd argue pretty much all the properties in the FormFieldControl should be signals.

.pipe(
startWith([undefined, undefined] as const),
map(() => [control.errorState, control.userAriaDescribedBy] as const),
pairwise(),
filter(([[prevErrorState, prevDescribedBy], [currentErrorState, currentDescribedBy]]) => {
return prevErrorState !== currentErrorState || prevDescribedBy !== currentDescribedBy;
}),
)
.subscribe(() => this._syncDescribedByIds());

this._valueChanges?.unsubscribe();

// Run change detection if the value changes.
Expand Down
12 changes: 12 additions & 0 deletions src/material/input/input.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -643,6 +643,18 @@ describe('MatMdcInput without forms', () => {
expect(input.getAttribute('aria-describedby')).toBe('start end');
}));

it('should preserve aria-describedby set directly in the DOM', fakeAsync(() => {
const fixture = createComponent(MatInputHintLabel2TestController);
const input = fixture.nativeElement.querySelector('input');
input.setAttribute('aria-describedby', 'custom');
fixture.componentInstance.label = 'label';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const hint = fixture.nativeElement.querySelector('.mat-mdc-form-field-hint');

expect(input.getAttribute('aria-describedby')).toBe(`${hint.getAttribute('id')} custom`);
}));

it('should set a class on the hint element based on its alignment', fakeAsync(() => {
const fixture = createComponent(MatInputMultipleHintTestController);

Expand Down
28 changes: 25 additions & 3 deletions src/material/input/input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ export class MatInput
private _webkitBlinkWheelListenerAttached = false;
private _config = inject(MAT_INPUT_CONFIG, {optional: true});

/** `aria-describedby` IDs assigned by the form field. */
private _formFieldDescribedBy: string[] | undefined;

/** Whether the component is being rendered on the server. */
readonly _isServer: boolean;

Expand Down Expand Up @@ -551,10 +554,29 @@ export class MatInput
* @docs-private
*/
setDescribedByIds(ids: string[]) {
if (ids.length) {
this._elementRef.nativeElement.setAttribute('aria-describedby', ids.join(' '));
const element = this._elementRef.nativeElement;
const existingDescribedBy = element.getAttribute('aria-describedby');
let toAssign: string[];

// In some cases there might be some `aria-describedby` IDs that were assigned directly,
// like by the `AriaDescriber` (see #30011). Attempt to preserve them by taking the previous
// attribute value and filtering out the IDs that came from the previous `setDescribedByIds`
// call. Note the `|| ids` here allows us to avoid duplicating IDs on the first render.
if (existingDescribedBy) {
const exclude = this._formFieldDescribedBy || ids;
toAssign = ids.concat(
existingDescribedBy.split(' ').filter(id => id && !exclude.includes(id)),
);
} else {
toAssign = ids;
}

this._formFieldDescribedBy = ids;

if (toAssign.length) {
element.setAttribute('aria-describedby', toAssign.join(' '));
} else {
this._elementRef.nativeElement.removeAttribute('aria-describedby');
element.removeAttribute('aria-describedby');
}
}

Expand Down
Loading