我有一个具有引导程序下拉列表的组件,我想关注下拉列表跨度上设置的当前周
我可以通过设置id来使用普通的javascript,然后使用Jquery .focus()方法来专注于此,但是我想知道是否有使用ViewChildren等方法使用它的7/7 +棱角分明的方法。
<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();
}
有关演示,请参见此堆叠闪电战。
如果单击时菜单不立即可见,则可以通过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();
}
});
}
有关演示,请参见此堆叠闪电战。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句