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

问题描述 投票:2回答:2

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

我可以通过设置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>

点击按钮,当前周刊聚焦。

javascript angular
2个回答
2
投票

您可以使用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


0
投票

请在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()函数中实现了更改检测。

© www.soinside.com 2019 - 2024. All rights reserved.