2 回答

TA贡献1779条经验 获得超6个赞
您可以使用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();
}
如果单击时菜单不立即可见,则可以通过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();
}
});
}

TA贡献1827条经验 获得超8个赞
请在html文件中添加以下代码
<ul class="dropdown-menu">
<li class="dropdown-item" [ngClass]="{'focus': currentWeek === week}" *ngFor="let week of weekList">
<a>
Week {{week}}
</a>
</li>
</ul>
在css文件中添加以下类
.focus{
background-color: red;
}
确保已在focusOnWeek()函数中实现了更改检测。
添加回答
举报