I need the screen reader to read "All Filters Are Removed" when all the filter items are removed. The tricky part is: when the active filter component is removed, there's no other element for me to set aria-label
to All filters are removed
. I was wondering how to force the screen reader to read something in this case?
The HTML Example is here:
<div *ngIf="activeFilters.length > 0">
<div class="active-filters" attr.aria-label="{{'List of active filters'}}">
<h4 class="active-filters-headline">{{'Active filters'}}</h4>
</div>
</div>
When all the filter items are removed, the active-filters
component will not show up. Because the activeFilters.length
would be 0. So I am not sure how to put aria-label
on the element that does not exist.
Here is the typescript code that could potentially introduce the screen reader logic:
ngAfterViewChecked() {
if (this.interaction && this.interactionDataDelivery) {
this.interaction = this.interactionDataDelivery = false;
if (this.activeFilters.length == 0) {
//How do I set up the aria-label?
}
}
}
CodePudding user response:
I've done this in the past by creating an element with aria-live="assertive"
, using some CSS trickery to have it hidden except for screen readers, and then setting its innerHTML
. Something along these lines:
const $message = document.createElement('span');
$message.classList.add('visuallyhidden'); // <-- Some method of making sure this element is only seen by screen readers
$message.setAttribute('aria-live', 'assertive');
document.body.appendChild($message);
const speak = function (message) {
$message.innerHTML = '';
window.setTimeout(() => {
$message.innerHTML = message;
}, 100);
};
You may also want to take some measures to ensure people using screen readers can't manually navigate to the alert message element as well, such as by clearing its content after the fact or perhaps by controlling its aria-hidden
attribute.