Home > Enterprise >  Accessibility and Angular: proper way to use aria-expanded and aria-controls - what options are acce
Accessibility and Angular: proper way to use aria-expanded and aria-controls - what options are acce

Time:01-27

If I validate this code on accessibility issues here https://validator.w3.org/nu/#textarea , then I don't have any errors:

<button aria-controls="t1" aria-expanded="false">Show</button>
<div id="t1">Some text</div>

Unfortunately, I use conditions ( *ngIf in Angular) which removes the <div> from the DOM until aria-expanded is true (myBoolValue is false when page loads):

<button aria-controls="t1" aria-expanded="myBoolValue">Show</button>
<div *ngIf="myBoolValue" id="t1">Some text</div>

As result, when validating, I get an error: Error: The aria-controls attribute must point to an element in the same document. which is clear: no id="t1" is in the DOM.

I should use some technique to make it different. As far as I understand, there might be several options (please correct):

Option 1 (to use an additional div as wrapper which always is in the DOM):

<button aria-controls="t1" aria-expanded="myBoolValue">Show</button>
<div id="t1"><div *ngIf="myBoolValue">Some text</div></div>

Option 2 (display: none; instead of removing from DOM):

<button aria-controls="t1" aria-expanded="myBoolValue">Show</button>
<div *ngClass="{hidden: !myBoolValue}" id="t1">Some text</div>

where .hidden {display: none;}

Option 3 (no aria-control - no errors):

<button aria-expanded="myBoolValue">Show</button>
<div *ngIf="myBoolValue">Some text</div>

Are Option 1, 2, 3 good enough? Is Option 3 valid at all? Is it an acceptable approach in case if Option 1 and Option 2 can't be easily implemented?

CodePudding user response:

It's better to have the aria-controls attribute and have it always pointing to an existing element if you can keep it that way. But all of your solutions are acceptable, even your #3.

Currently, assistive tools don't actually use aria-controls a lot. Some of them provide shortcut to quickly switch from controlling to controlled element and back, but that's almost all. Therefore it's not a big loss if you must remove it completely as in your solution #3.

However, we can never imagine what aria-controls may be used for in the future, and so, solutions #1 and #2 would certainly be better than #3 at long term, if you can do it. Just in case.

Solution #2 is maybe slightly better than #1 because you are sure to don't break anything. It could have an importance if the controlled element is interactive and focusable. Focusing the parent instead wouldn't make sense and it could cause subtle focus issues afterwards. IN the other hand, you are guaranteed by the standard that display:none always means never rendered at all, whatever the kind of rendering it could be (screen, speech, braille, or whatever hasn't yet been invented).

So, by order of preference, I would recommend #2, #1, #3.

  • Related