Accessibility in Angular Forms
Explain how to implement accessible forms in Angular, including proper ARIA attributes and accessible error handling.
import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-accessible-form',
template: `
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
<label for="name">Name:</label>
<input type="text" id="name" formControlName="name" aria-describedby="name-error" />
<span id="name-error" *ngIf="profileForm.get('name').touched && profileForm.get('name').invalid">Name is required.</span>
<button type="submit">Submit</button>
</form>
`,
})
export class AccessibleFormComponent {
profileForm = this.fb.group({
name: ['', Validators.required],
});
constructor(private fb: FormBuilder) {}
onSubmit() {
// Handle form submission
}
}
This Angular component uses FormBuilder to create a form with a single required 'name' field. The template includes an accessible label and uses ARIA attributes to connect the input field with an error message span. This span is only shown if the 'name' field is touched and invalid. When the form is submitted, the onSubmit method is invoked.