118

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?

Yuri
  • 4,254
  • 1
  • 29
  • 46
namrata
  • 2,235
  • 5
  • 28
  • 35

4 Answers4

222

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

Bruno João
  • 5,105
  • 2
  • 21
  • 26
  • 3
    it should be `[attr.aria-label]="productDetails?.ProductName"` – Luca De Nardi May 27 '19 at 09:11
  • @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. – Bruno João Jul 10 '19 at 12:56
  • 4
    @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. – Luca De Nardi Jul 11 '19 at 13:09
  • 2
    @LucaDeNardi thanks for letting me know. I've removed the brackets. – Bruno João Jul 11 '19 at 17:34
  • @BrunoJoão the ideal way is to use square brackets. – River CR Phoenix Oct 01 '19 at 08:24
  • 1
    if anyone is wondering, works for labelledby as well: `[attr.aria-labelledby]` – Bullsized Feb 14 '23 at 09:47
7

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

[attr.aria-label]="'Product details for' + productDetails?.ProductName"
Kabb5
  • 3,760
  • 2
  • 33
  • 55
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..

Nɪsʜᴀɴᴛʜ ॐ
  • 2,756
  • 4
  • 33
  • 57
-2

this works for me without [].

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

Yuri
  • 4,254
  • 1
  • 29
  • 46
MMGuz
  • 62
  • 4