我有一个具有引导下拉列表的组件,我想关注下拉范围内设置的当前周
我可以通过设置id使用普通的javascript,然后使用Jquery .focus()方法来关注它,但想知道是否有任何角度7/7+方式使用ViewChildren等。
<button class="btn dropdown-toggle"
(click)="focusOnWeek(currentWeek)"
type="button" data-toggle="dropdown">
<span>Week {{currentWeek}}</span> // currentWeek = 5 need to focus on week 5 <a> tag on click of this span
</button>
<ul class="dropdown-menu">
<li *ngFor="let week of weekList">//weekList = [1,2,3,4,5,6,7,8,9,10]>
<a class="dropdown-item"
Week {{week}}
</a>
</li>
</ul>
点击按钮,当前周刊聚焦。
您可以使用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();
}
有关演示,请参阅this stackblitz。
如果单击时菜单未立即显示,则可以使用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();
}
});
}
有关演示,请参阅this stackblitz。
请在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()函数中实现了更改检测。