如何使用 ARIA 属性标记 *ngIf 块?

How to label *ngIf blocks with ARIA attributes?

我想知道如何根据 WAI-ARIA 规范用 ARIA 属性标记我的 Angular 应用程序。假设我有以下模板,

<div id="no-1" *ngIf="some_condition">some text</div>
<div id="no-2" *ngIf=!some_condition">some other text</div>

<button (click)="some_condition = !some_condition">switch</button>

用 ARIA 属性标记这些元素的正确方法是什么?我的理解是 *ngIf 完全从 DOM 中删除了元素,所以 aria-hidden 是否需要在任何一个 div 上?当 aria-hidden 为真时,两个元素都不会出现在 DOM 中,因此这似乎毫无意义。不过,我不确定它是否对屏幕阅读器有帮助,所以我想确定一下。

其次,由于两个div根据some_condition的值在DOM中填充了相同的位置,所以它们应该具有相同的ID吗?按钮是否应该有一个指向该 ID 的 aria-controls?如果不是,如何指定div和按钮之间的关系?

It's my understanding *ngIf removes the element from the DOM altogether, so is an aria-hidden necessary on either of the divs?

正确;该元素将不存在于页面上,因此 aria-hidden 不是必需的。

Second, since both divs fill the same position in the DOM based on the value of some_condition, should they both have the same ID?

如果您不需要任何特定的 ID,那么最好避免重复 ID,但当它们不同时显示时不会有任何坏处。

And should the button have an aria-controls that refers to that ID? If not, how do I specify the relationship between the divs and the button?

包含 aria-controls 是个好主意。如果两个 div 使用相同的 ID,那么它是直接的。

<div id="no-1">...</div>
<button attr.aria-controls="no-1">Click Me!</button>

如果 div 使用不同的 ID,那么它仍然很简单,但是您需要在组件 TS 或内联中使用一些逻辑,如下所示:

<div id="no-1" *ngIf="some_condition">some text</div>
<div id="no-2" *ngIf=!some_condition">some other text</div>

<button [attr.aria-controls]="some_condition ? 'no-1' : 'no-2'">Click Me!</button>

注意我是如何定义 ARIA 属性的。在 angular 中,您应该在属性前添加 attr. 这适用于您要添加的任何 ARIA 属性。一些例子:

<!-- this assigns the label inline HTML -->
<section attr.aria-label="This section is important"></section>

<!-- this expects a variable called myLabelVariable to be defined in the component -->
<section [attr.aria-label]="myLabelVariable"></section>