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

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


我可以通过设置id,然后使用Jquery .focus()方法将其放在焦点上,用普通的javascript来做,但是想知道是否有使用ViewChildren等的7 / 7+棱角分明的方法来做。


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

在“单击按钮”上,将聚焦“当前周”。


明月笑刀无情
浏览 243回答 2
2回答

哆啦的时光机

您可以使用ViewChildren查找要聚焦的锚元素。首先,您#anchor在锚元素上设置模板参考变量(例如):<ul class="dropdown-menu">&nbsp; <li *ngFor="let week of weekList">&nbsp; &nbsp; <a #anchor class="dropdown-item">Week {{week}}</a>&nbsp; </li></ul>在代码中,您可以使用引用锚元素ViewChildren:@ViewChildren("anchor") anchorList: QueryList<ElementRef>;然后将焦点放在对应于指定星期的锚点上:focusOnWeek(week) {&nbsp; const weekIndex = this.weekList.indexOf(week);&nbsp; const elementRef = this.anchorList.find((item, index) => index === weekIndex);&nbsp; elementRef.nativeElement.focus();}如果单击时菜单不立即可见,则可以通过QueryList.changes事件监视菜单项的创建。当检测到可见项目时,可以使用设置焦点currentWeek。ngAfterViewInit() {&nbsp; this.anchorList.changes.subscribe(() => {&nbsp; &nbsp; if (this.anchorList.length > 0) {&nbsp; &nbsp; &nbsp; const weekIndex = this.weekList.indexOf(this.currentWeek);&nbsp; &nbsp; &nbsp; const elementRef = this.anchorList.find((item, index) => index === weekIndex);&nbsp; &nbsp; &nbsp; elementRef.nativeElement.focus();&nbsp; &nbsp; }&nbsp; });}

斯蒂芬大帝

请在html文件中添加以下代码&nbsp;<ul class="dropdown-menu">&nbsp; &nbsp; &nbsp; <li class="dropdown-item" [ngClass]="{'focus': currentWeek === week}" *ngFor="let week of weekList">&nbsp; &nbsp; &nbsp; &nbsp; <a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Week {{week}}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; </ul>在css文件中添加以下类.focus{&nbsp; &nbsp;background-color: red;}确保已在focusOnWeek()函数中实现了更改检测。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript