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

dot*_*pro 5 javascript angular

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

我可以通过设置 ids 使用纯 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>
Run Code Online (Sandbox Code Playgroud)

单击按钮后,当前周将成为焦点。

Con*_*Fan 4

您可以使用它ViewChildren来查找您想要聚焦的锚元素。#anchor首先,在锚元素上设置模板引用变量(例如):

<ul class="dropdown-menu">
  <li *ngFor="let week of weekList">
    <a #anchor class="dropdown-item">Week {{week}}</a>
  </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

在代码中,您可以使用以下命令获取对锚元素的引用ViewChildren:

@ViewChildren("anchor") anchorList: QueryList<ElementRef>;
Run Code Online (Sandbox Code Playgroud)

然后将焦点设置在与指定周相对应的锚点上:

focusOnWeek(week) {
  const weekIndex = this.weekList.indexOf(week);
  const elementRef = this.anchorList.find((item, index) => index === weekIndex);
  elementRef.nativeElement.focus();
}
Run Code Online (Sandbox Code Playgroud)

请参阅此 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();
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

请参阅此 stackblitz的演示。