通过 ngIf 出现后聚焦元素

Joh*_*ery 10 focus typescript angular-ng-if angular

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

// 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>
Run Code Online (Sandbox Code Playgroud)
// 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
}
Run Code Online (Sandbox Code Playgroud)

如果我在确认按钮上单击或按下 Enter,焦点会在原始按钮出现后立即移动到原始按钮,但是如果我在输入字段中按下 Enter,按钮就会出现,但由于某种原因,在我移动鼠标之前它不会获得焦点. 我如何让它立即对两者都起作用?

Con*_*Fan 6

当按钮被添加到视图或从视图中删除时,您可以使用ViewChildrenQueryList.changes要通知的事件。如果QueryList包含按钮元素,您可以将焦点设置在它上面。有关演示,请参阅此 stackblitz。建议:当输入字段可见时,您可能需要做一些类似的事情来将焦点设置在输入字段上。

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
  }
}
Run Code Online (Sandbox Code Playgroud)