为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

明月笑刀无情 2021-04-16 14:11:23
我有一个具有引导程序下拉列表的组件,我想关注下拉列表跨度上设置的当前周我可以通过设置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>在“单击按钮”上,将聚焦“当前周”。
查看完整描述

2 回答

?
哆啦的时光机

TA贡献1779条经验 获得超6个赞

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

}

如果单击时菜单不立即可见,则可以通过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();

    }

  });

}


查看完整回答
反对 回复 2021-04-29
?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

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


查看完整回答
反对 回复 2021-04-29
  • 2 回答
  • 0 关注
  • 242 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信