2 回答

TA貢獻(xiàn)1779條經(jīng)驗 獲得超6個贊
您可以使用ViewChildren查找要聚焦的錨元素。首先,您#anchor在錨元素上設(shè)置模板參考變量(例如):
<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>;
然后將焦點放在對應(yīng)于指定星期的錨點上:
focusOnWeek(week) {
const weekIndex = this.weekList.indexOf(week);
const elementRef = this.anchorList.find((item, index) => index === weekIndex);
elementRef.nativeElement.focus();
}
如果單擊時菜單不立即可見,則可以通過QueryList.changes事件監(jiān)視菜單項的創(chuàng)建。當(dāng)檢測到可見項目時,可以使用設(shè)置焦點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貢獻(xiàn)1827條經(jīng)驗 獲得超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()函數(shù)中實現(xiàn)了更改檢測。
添加回答
舉報