Javascript 如何在不使用Js id选择器的情况下动态获取*ngFor中的元素
我有一个组件有一个引导下拉列表,我想把重点放在当前一周的下拉列表上 我可以通过设置id,然后使用Jquery.focus()方法来使用普通javascript来实现,但我想知道是否有任何角度7/7+的方法可以使用ViewChildren等来实现Javascript 如何在不使用Js id选择器的情况下动态获取*ngFor中的元素,javascript,angular,Javascript,Angular,我有一个组件有一个引导下拉列表,我想把重点放在当前一周的下拉列表上 我可以通过设置id,然后使用Jquery.focus()方法来使用普通javascript来实现,但我想知道是否有任何角度7/7+的方法可以使用ViewChildren等来实现 <button class="btn dropdown-toggle" (click)="focusOnWeek(currentWeek)" type="button" data-toggle="dropdown"&
<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>
Week{{currentWeek}//currentWeek=5需要在单击此跨度时关注Week 5标记
- //每周列表=[1,2,3,4,5,6,7,8,9,10]>
请在html文件中添加以下代码
<ul class="dropdown-menu">
<li class="dropdown-item" [ngClass]="{'focus': currentWeek === week}" *ngFor="let week of weekList">
<a>
Week {{week}}
</a>
</li>
</ul>
确保在focusOnWeek()函数中实现了更改检测。您可以使用ViewChildren
查找要聚焦的锚元素。首先,在锚元素上设置模板引用变量(例如,#anchor
):
<ul class="dropdown-menu">
<li *ngFor="let week of weekList">
<a #anchor class="dropdown-item">Week {{week}}</a>
</li>
</ul>
然后将焦点设置在与指定周相对应的锚点上:
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();
}
});
}
请参阅演示。是我还是您的ngFor在错误的元素上。我猜你会想要一个多列表元素,里面有一个锚吗?我更新了代码,使用引导而不是SetTimeout来显示下拉列表,并创建了一个新的Stackoverflow问题
focusOnWeek(week) {
const weekIndex = this.weekList.indexOf(week);
const elementRef = this.anchorList.find((item, index) => index === weekIndex);
elementRef.nativeElement.focus();
}
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();
}
});
}