gpt4 book ai didi

javascript - 如何在不使用Js id选择器的情况下动态获取Angular * ngFor中的元素

转载 作者:行者123 更新时间:2023-11-29 10:27:20 25 4
gpt4 key购买 nike

我有一个具有引导下拉列表的组件,我想关注在下拉列表范围内设置的当前周

我可以通过设置 id 使用纯 javascript 来完成它,然后使用 Jquery .focus() 方法来关注它,但想知道是否有任何 Angular 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 元素。首先,在 anchor 元素上设置模板引用变量(例如 #anchor):

<ul class="dropdown-menu">
<li *ngFor="let week of weekList">
<a #anchor class="dropdown-item">Week {{week}}</a>
</li>
</ul>

在代码中,您使用 ViewChildren 获得对 anchor 元素的引用:

@ViewChildren("anchor") anchorList: QueryList<ElementRef>;

然后您将焦点设置在对应于指定周的 anchor 上:

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用于演示。

关于javascript - 如何在不使用Js id选择器的情况下动态获取Angular * ngFor中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55659889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com