通过 ngIf 出现后聚焦元素

2024-03-27

我有一个按钮,单击该按钮时,该按钮会替换为输入字段和确认按钮,然后当输入完成时,它会再次替换为原始按钮。发生这种情况时,我希望它在出现后将焦点集中在原始按钮上(一些用户请求更好地支持选项卡导航),但我似乎无法让它始终如一地做到这一点。我能做的最好的事情就是:

// component.html
<button #durationButton *ngIf="!enteringDuration" (click)="enterDuration()">Enter Duration</button>
<ng-container *ngIf="enteringDuration">
    <input type="number" [(ngModel)]="duration" (keyup.enter)="setDuration()">
    <button (click)="setDuration()">&#10003;</button>
</ng-container>
// component.ts
@ViewChild("durationButton") durationButton: ElementRef
duration: number
enteringDuration = false
shouldFocusDurationButton = false

ngAfterContentChecked () {
    if (this.shouldFocusDurationButton && this.durationButton) {
        this.shouldFocusDurationButton = false
        this.durationButton.nativeElement.focus()
    }
}

enterDuration () {
    this.enteringDuration = true
}
setDuration () {
    this.enteringDuration = false
    this.shouldFocusDurationButton = true
}

如果我在确认按钮上单击或按 Enter 键,焦点一出现就会移到原始按钮,但如果我在输入字段中按 Enter 键,该按钮就会出现,但由于某种原因,直到我移动鼠标它才会获得焦点。我怎样才能让它立即对两者起作用?


您可以使用ViewChildrenQueryList.changes当按钮添加到视图或从视图中删除时要通知的事件。如果QueryList包含按钮元素,您可以将焦点设置在其上。看这次堆栈闪电战 https://stackblitz.com/edit/angular-frvpev进行演示。建议:您可能需要执行类似的操作,以便在输入字段可见时将焦点设置在输入字段上。

import { Component, ViewChildren, ElementRef, AfterViewInit, QueryList } from '@angular/core';
...

export class AppComponent implements AfterViewInit {

  @ViewChildren("durationButton") durationButton: QueryList<ElementRef>;

  enteringDuration = false

  ngAfterViewInit() {
    this.setFocus(); // If the button is already present...
    this.durationButton.changes.subscribe(() => {
      this.setFocus();
    });
  }

  setFocus() {
    if (this.durationButton.length > 0) {
      this.durationButton.first.nativeElement.focus();
    }
  }

  enterDuration() {
    this.enteringDuration = true
  }

  setDuration() {
    this.enteringDuration = false
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 ngIf 出现后聚焦元素 的相关文章

随机推荐