您可以使用ViewChildren
找到您想要关注的锚元素。首先,设置一个模板引用变量(例如#anchor
)在锚元素上:
<ul class="dropdown-menu">
<li *ngFor="let week of weekList">
<a #anchor class="dropdown-item">Week {{week}}</a>
</li>
</ul>
在代码中,您可以使用以下命令获取对锚元素的引用ViewChildren
:
@ViewChildren("anchor") anchorList: QueryList<ElementRef>;
然后将焦点设置在与指定周相对应的锚点上:
focusOnWeek(week) {
const weekIndex = this.weekList.indexOf(week);
const elementRef = this.anchorList.find((item, index) => index === weekIndex);
elementRef.nativeElement.focus();
}
See 这次堆栈闪电战 https://stackblitz.com/edit/angular-e63zih?file=src%2Fapp%2Fapp.component.ts进行演示。
如果单击时菜单没有立即可见,您可以使用以下命令监视菜单项的创建:QueryList.changes
事件。当您检测到项目可见时,您可以使用以下命令设置焦点currentWeek
.
ngAfterViewInit() {
this.anchorList.changes.subscribe(() => {
if (this.anchorList.length > 0) {
const weekIndex = this.weekList.indexOf(this.currentWeek);
const elementRef = this.anchorList.find((item, index) => index === weekIndex);
elementRef.nativeElement.focus();
}
});
}
See 这次堆栈闪电战 https://stackblitz.com/edit/angular-nx5dh2?file=src%2Fapp%2Fapp.component.ts进行演示。