Skip to content
Open
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
23 changes: 22 additions & 1 deletion src/material/form-field/directives/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@
* found in the LICENSE file at https://angular.dev/license
*/

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

/**
Expand All @@ -21,10 +28,24 @@ 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}],
})
export class MatError {
@Input() id: string = inject(_IdGenerator).getId('mat-mdc-error-');

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');
}
}
}
2 changes: 1 addition & 1 deletion src/material/form-field/form-field.html
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@
}
</div>

<div aria-atomic="true" aria-live="polite"
<div
class="mat-mdc-form-field-subscript-wrapper mat-mdc-form-field-bottom-align"
[class.mat-mdc-form-field-subscript-dynamic-size]="subscriptSizing === 'dynamic'"
>
Expand Down
6 changes: 2 additions & 4 deletions src/material/input/input.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1276,13 +1276,11 @@ describe('MatInput with forms', () => {
.toBe(1);
});

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

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

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