To apply dynamic aria-label
you can either use [aria-label]
or [attr.aria-label]
. Both of these vary for different mat-input
types. You can read more about it here.
If you add [attr.aria-label]
to mat-datepicker-toggler
it will apply dynamic aria-label
to only this tag. To add dynamic aria-label
to the child button
element inside it you'll have to use typescript
.
You can do that by writing this code in the .ts
file of your component within ngAfterViewInit
as follows:
datepicker-component.html
<mat-form-field appearance="fill">
<mat-label>Choose a date</mat-label>
<input matInput [matDatepicker]="picker1" [formControl]="date" />
<mat-datepicker-toggle
matSuffix
[for]="picker1"
attr.aria-label="{{ 'Selected date is ' + date.value }}"
></mat-datepicker-toggle>
<mat-datepicker #picker1></mat-datepicker>
</mat-form-field>
datepicker-component.ts
date = new FormControl(moment([2017, 0, 1]));
ngAfterViewInit(): void {
const matTogglerChild = document.querySelector(
'mat-datepicker-toggle'
)?.firstElementChild;
const ariaLabelText = 'Selected Date is ' + moment(this.date.value).format('MM/DD/YYYY');
matTogglerChild?.setAttribute('aria-label', ariaLabelText);
}
So, in this above code, I get the immediate child of mat-datepicker-toggler
and then assign it a new aria-label. You can do the same for the other elements inside the mat-datepicker
. I've implemented this inside ngAfterViewInit
because the view doesn't get rendered in ngOnInit
, so it'll return undefined
.
I hope this helps you. Let me know if you need any more clarifications.