[英]Retain a11y focus functionality with ng-content
Angular 9 和 Angular 材料
我将mat-chip-list
包装在foo-chip-list
元素中。 但是,我失去了箭头 function 指向下一个芯片的 a11y 功能。 无论如何保留该功能而不必重新编码 mat-chip-list 中已经编码的内容?
此外,cdk 门户而不是 ng-content 是否是一种我可以传递芯片元素并仍保留原始 mat-chip-list a11y 功能(如箭头)的方式?
foo-chip-list 元素:
<mat-chip-list
[aria-orientation]= "ariaOrientation"
[multiple]="multiple"
[selectable]="selectable"
class="atlas-chip-list"
[ngClass]="{'mat-chip-list-stacked' : ariaOrientation == 'vertical'}">
<ng-content></ng-content>
</mat-chip-list>
我设法做到了这一点,但您需要使用@HostListener
,这可能会影响您应用程序的其他部分。
在您的FooChipListComponent
中,添加以下内容:
@ContentChildren(MatChip, { descendants: true }) chips: QueryList<MatChip>;
_keyManager: FocusKeyManager<MatChip>;
@HostListener('keydown', ['$event'])
keydown(event: any) {
this._keyManager.onKeydown(event);
}
ngAfterContentInit() {
this._keyManager = new FocusKeyManager<MatChip>(this.chips)
.withWrap()
.withVerticalOrientation()
.withHomeAndEnd()
.withHorizontalOrientation('ltr');
}
这使用 Material 的FocusKeyManager
中的 FocusKeyManager 在<ng-content>
元素被芯片替换后在芯片上设置键盘焦点/导航。 @ContentChildren
负责获取筹码 - 我们需要使用 ContentChildren 而不是 ViewChildren,因为我们正在使用<ng-content>
。
keydown
方法将 keydown 事件传递给FocusKeyManager
,当您按下方向箭头键时,它将负责导航。
我制作了一个有效的 StackBlitz 演示。 如果您在foo-chip-list.component.ts
ariaOrientation
的值更改为vertical
,您将看到它如何与堆叠的芯片一起工作。
更新:发布上述解决方案后,我发现了一个问题。 在演示中,单击第 3 个筹码(“Primary Fish”)并按向右箭头。 您会注意到选择现在移动到第一个筹码而不是第四个筹码。 这是因为当您使用鼠标到 select 时, activeItemIndex
不会更新。 为了解决这个问题,我在组件中进行了以下更改,其中我定义了要用作 ng-content 的芯片:
<foo-chip-list #chipList>
<mat-chip (click)="selectChip(0)">One fish</mat-chip>
<mat-chip (click)="selectChip(1)">Two fish</mat-chip>
<mat-chip (click)="selectChip(2)">Primary fish</mat-chip>
<mat-chip (click)="selectChip(3)">Accent fish</mat-chip>
</foo-chip-list>
并在该组件的 Typescript 中:
@ViewChild('chipList') chipList: FooChipList;
selectChip(index: number) {
this.chipList.updateSelection(index);
}
然后在FooChipList
我添加了以下方法:
updateSelection(index: number) {
this._keyManager.setActiveItem(index);
}
这意味着当点击芯片时,它会更新密钥管理器中的活动项目,因此键盘导航工作。 请参阅此 StackBlitz进行演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.