如何在不使用Js id选择器的情况下在Angular中动态获取* ngFor中的元素 [英] How to get an element in *ngFor in Angular dynamically without using Js id selector

查看:101
本文介绍了如何在不使用Js id选择器的情况下在Angular中动态获取* ngFor中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有引导程序下拉列表的组件,我想关注下拉列表跨度中设置的当前周

I have a component that has a bootstrap dropdown, I want to focus on the current week that is set on the dropdown span

我可以通过设置id来使用普通的javascript,然后使用Jquery .focus()方法来专注于它,但是我想知道是否有使用ViewChildren等方法的任何角度7/7+方式.

I can do it with plain javascript by setting ids, and then using Jquery .focus() method to focus on it, But wanted to know if there is any angular 7/ 7+ way to do it using ViewChildren etc.

<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>

单击当前星期"按钮即可.

On Click of Button the Currentweek is focused.

推荐答案

您可以使用ViewChildren查找要聚焦的锚点元素.首先,您在锚元素上设置模板参考变量(例如#anchor):

You can use ViewChildren to find the anchor element that you want to focus. First, you set a template reference variable (e.g. #anchor) on the anchor elements:

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

在代码中,您可以使用ViewChildren来引用锚元素:

In the code, you get a reference to the anchor elements with ViewChildren:

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

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

and you set the focus on the anchor that corresponds to the specified week:

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

请参阅此stackblitz 演示.

如果在单击时没有立即显示菜单,则可以使用QueryList.changes事件监视菜单项的创建.当您检测到可见的项目时,可以使用currentWeek设置焦点.

If the menu is not immediately visible when the click is made, you can monitor the creation of the menu items with the QueryList.changes event. When you detect that the items are visible, you can then set the focus with 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();
    }
  });
}

请参见此stackblitz 演示.

这篇关于如何在不使用Js id选择器的情况下在Angular中动态获取* ngFor中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆