代码之家  ›  专栏  ›  技术社区  ›  dota2pro Matej

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

  •  0
  • dota2pro Matej  · 技术社区  · 7 年前

    我可以用普通的javascript设置id,然后使用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>
    

    按一下按钮,当前的一周是重点。

    2 回复  |  直到 7 年前
        1
  •  3
  •   ConnorsFan    7 年前

    你可以用 ViewChildren 找到要聚焦的锚元素。首先,设置一个模板引用变量(例如。 #anchor )在锚定元件上:

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

    在代码中,可以使用 查看子项

    @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

        2
  •  0
  •   Armin    7 年前

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

    推荐文章