How to bind dynamic data to aria-label?
Asked Answered
D

4

128

I have dynamic text to bind to aria-label on a HTML page. This is an Angular 2 app. I am using something like this:

aria-label="Product details for {{productDetails?.ProductName}}"

But I get an error:

Can't bind to 'aria-label' since it isn't a known property of 'div'.

Is there any workaround for this?

Distributary answered 7/3, 2017 at 21:37 Comment(0)
P
246

Just use attr. before aria-label:

attr.aria-label="Product details for {{productDetails?.ProductName}}"

or

[attr.aria-label]="'Product details for ' + productDetails?.ProductName"

Examples here: https://stackblitz.com/edit/angular-aria-label?embed=1&file=src/app/app.component.html&hideExplorer=1

Ps. As @Simon_Weaver mentioned, there are some components that implements its own aria-label @Input, like mat-select.

See his answer here Angular Material mat-label accessibility

Partridgeberry answered 7/3, 2017 at 21:45 Comment(6)
it should be [attr.aria-label]="productDetails?.ProductName"Lattimer
@LucaDeNardi, actually, your way is less readable and you forgot to add the static string part Product details for.... I've added your suggested selector for anyone who wants the best fit for their case.Eddyede
@BrunoJoão sorry, I meant that you should not use [attr.aria-label] and {{productDetails}} together, since the square brackets already resolve variables. You either write your attribute without square brackets and with curly brackets, or your attribute with square brackets and without curly ones.Lattimer
@LucaDeNardi thanks for letting me know. I've removed the brackets.Eddyede
@BrunoJoão the ideal way is to use square brackets.Gervais
if anyone is wondering, works for labelledby as well: [attr.aria-labelledby]Dose
N
7

You should use square brackets ([ ]) around the target property:

[attr.aria-label]="'Product details for' + productDetails?.ProductName"
Nerty answered 2/7, 2019 at 18:57 Comment(0)
W
4

Also this could be further checked if ProductName in productDetails is null or undefined as

[attr.aria-label]="(typeof productDetails.ProductName !== 'undefined') ? 
'Product details for ' + productDetails.ProductName : '' "

So that the JAWS/NVDA/Narrator could able to read if it's value is present or not..

Woollyheaded answered 23/2, 2021 at 8:8 Comment(0)
M
-2

this works for me without [].

attr.aria-labelledby="navbarDropdownMenuLink{{ i }}"

Mesomorph answered 5/7, 2020 at 19:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.