Skip to content

fix(material/form-field): move error aria-live to parent container #30678

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

Merged
merged 1 commit into from
Mar 28, 2025
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
2 changes: 1 addition & 1 deletion goldens/material/form-field/index.api.md
Original file line number Diff line number Diff line change
@@ -80,8 +80,8 @@ export class MatFormField implements FloatingLabelParent, AfterContentInit, Afte
// (undocumented)
_formFieldControl: MatFormFieldControl_2<any>;
getConnectedOverlayOrigin(): ElementRef;
_getDisplayedMessages(): 'error' | 'hint';
getLabelId: i0.Signal<string | null>;
_getSubscriptMessageType(): 'error' | 'hint';
_handleLabelResized(): void;
// (undocumented)
_hasFloatingLabel: i0.Signal<boolean>;
2 changes: 1 addition & 1 deletion goldens/material/input/index.api.md
Original file line number Diff line number Diff line change
@@ -73,8 +73,8 @@ export class MatFormField implements FloatingLabelParent, AfterContentInit, Afte
// (undocumented)
_formFieldControl: MatFormFieldControl<any>;
getConnectedOverlayOrigin(): ElementRef;
_getDisplayedMessages(): 'error' | 'hint';
getLabelId: i0.Signal<string | null>;
_getSubscriptMessageType(): 'error' | 'hint';
_handleLabelResized(): void;
// (undocumented)
_hasFloatingLabel: i0.Signal<boolean>;
2 changes: 1 addition & 1 deletion goldens/material/select/index.api.md
Original file line number Diff line number Diff line change
@@ -96,8 +96,8 @@ export class MatFormField implements FloatingLabelParent, AfterContentInit, Afte
// (undocumented)
_formFieldControl: MatFormFieldControl_2<any>;
getConnectedOverlayOrigin(): ElementRef;
_getDisplayedMessages(): 'error' | 'hint';
getLabelId: i0.Signal<string | null>;
_getSubscriptMessageType(): 'error' | 'hint';
_handleLabelResized(): void;
// (undocumented)
_hasFloatingLabel: i0.Signal<boolean>;
4 changes: 3 additions & 1 deletion src/material/chips/chip-grid.spec.ts
Original file line number Diff line number Diff line change
@@ -983,7 +983,9 @@ describe('MatChipGrid', () => {
errorTestComponent.formControl.markAsTouched();
fixture.detectChanges();

expect(containerEl.querySelector('mat-error')!.getAttribute('aria-live')).toBe('polite');
expect(
containerEl.querySelector('[aria-live]:has(mat-error)')!.getAttribute('aria-live'),
).toBe('polite');
});

it('sets the aria-describedby on the input to reference errors when in error state', fakeAsync(() => {
21 changes: 2 additions & 19 deletions src/material/form-field/directives/error.ts
Original file line number Diff line number Diff line change
@@ -6,14 +6,7 @@
* found in the LICENSE file at https://angular.dev/license
*/

import {
Directive,
ElementRef,
InjectionToken,
Input,
HostAttributeToken,
inject,
} from '@angular/core';
import {Directive, InjectionToken, Input, inject} from '@angular/core';
import {_IdGenerator} from '@angular/cdk/a11y';

/**
@@ -28,7 +21,6 @@ export const MAT_ERROR = new InjectionToken<MatError>('MatError');
selector: 'mat-error, [matError]',
host: {
'class': 'mat-mdc-form-field-error mat-mdc-form-field-bottom-align',
'aria-atomic': 'true',
'[id]': 'id',
},
providers: [{provide: MAT_ERROR, useExisting: MatError}],
@@ -38,14 +30,5 @@ export class MatError {

constructor(...args: unknown[]);

constructor() {
const ariaLive = inject(new HostAttributeToken('aria-live'), {optional: true});

// If no aria-live value is set add 'polite' as a default. This is preferred over setting
// role='alert' so that screen readers do not interrupt the current task to read this aloud.
if (!ariaLive) {
const elementRef = inject(ElementRef);
elementRef.nativeElement.setAttribute('aria-live', 'polite');
}
}
constructor() {}
}
30 changes: 19 additions & 11 deletions src/material/form-field/form-field.html
Original file line number Diff line number Diff line change
@@ -96,25 +96,33 @@
</div>

<div
class="mat-mdc-form-field-subscript-wrapper mat-mdc-form-field-bottom-align"
[class.mat-mdc-form-field-subscript-dynamic-size]="subscriptSizing === 'dynamic'"
class="mat-mdc-form-field-subscript-wrapper mat-mdc-form-field-bottom-align"
[class.mat-mdc-form-field-subscript-dynamic-size]="subscriptSizing === 'dynamic'"
>
@switch (_getDisplayedMessages()) {
@case ('error') {
<div class="mat-mdc-form-field-error-wrapper">
@let subscriptMessageType = _getSubscriptMessageType();

<!--
Use a single permanent wrapper for both hints and errors so aria-live works correctly,
as having it appear post render will not consistently work. We also do not want to add
additional divs as it causes styling regressions.
-->
<div aria-atomic="true" aria-live="polite"
[class.mat-mdc-form-field-error-wrapper]="subscriptMessageType === 'error'"
[class.mat-mdc-form-field-hint-wrapper]="subscriptMessageType === 'hint'"
>
@switch (subscriptMessageType) {
@case ('error') {
<ng-content select="mat-error, [matError]"></ng-content>
</div>
}
}

@case ('hint') {
<div class="mat-mdc-form-field-hint-wrapper">
@case ('hint') {
@if (hintLabel) {
<mat-hint [id]="_hintLabelId">{{hintLabel}}</mat-hint>
}
<ng-content select="mat-hint:not([align='end'])"></ng-content>
<div class="mat-mdc-form-field-hint-spacer"></div>
<ng-content select="mat-hint[align='end']"></ng-content>
</div>
}
}
}
</div>
</div>
6 changes: 3 additions & 3 deletions src/material/form-field/form-field.ts
Original file line number Diff line number Diff line change
@@ -615,8 +615,8 @@ export class MatFormField
return control && control[prop];
}

/** Determines whether to display hints or errors. */
_getDisplayedMessages(): 'error' | 'hint' {
/** Gets the type of subscript message to render (error or hint). */
_getSubscriptMessageType(): 'error' | 'hint' {
return this._errorChildren && this._errorChildren.length > 0 && this._control.errorState
? 'error'
: 'hint';
@@ -684,7 +684,7 @@ export class MatFormField
ids.push(...this._control.userAriaDescribedBy.split(' '));
}

if (this._getDisplayedMessages() === 'hint') {
if (this._getSubscriptMessageType() === 'hint') {
const startHint = this._hintChildren
? this._hintChildren.find(hint => hint.align === 'start')
: null;
6 changes: 4 additions & 2 deletions src/material/input/input.spec.ts
Original file line number Diff line number Diff line change
@@ -1266,11 +1266,13 @@ describe('MatMdcInput with forms', () => {
.toBe(1);
}));

it('should set the proper aria-live attribute on the error messages', fakeAsync(() => {
it('should be in a parent element with the an aria-live attribute to announce the error', fakeAsync(() => {
testComponent.formControl.markAsTouched();
fixture.detectChanges();

expect(containerEl.querySelector('mat-error')!.getAttribute('aria-live')).toBe('polite');
expect(
containerEl.querySelector('[aria-live]:has(mat-error)')!.getAttribute('aria-live'),
).toBe('polite');
}));

it('sets the aria-describedby to reference errors when in error state', fakeAsync(() => {
Loading