在 angular 9 中单击按钮时在输入字段上自动对焦

Autofocus on an input field on button click in angular 9

我在组件内的两个不同位置添加了按钮。单击按钮时,将显示输入字段。我尝试了多种方法来实现这一点,如下所示:

在输入字段上使用了自动对焦属性 - 因为我在屏幕上有两个按钮,自动对焦似乎不起作用。

使用了 .focus() 方法 -

HTML 文件

<button (click) = "addUser()">Add User</button>

<input *ngIf="showInputField" #userName />

TS 文件

@ViewChild('userName') userName:ElementRef;
addUser() { this.showInputField=true; this.userName.nativeElement.focus(); }

在第二种情况下,我收到错误“无法读取未定义的 属性 nativeElement”,这是因为 HTML 在方法执行完成后加载。

这可能不是最佳解决方案,但您可以使用 setTimeout() 等待布尔值更改。

addUser() {
  this.showInputField = true;
  setTimeout(() => this.userName.nativeElement.focus());
}

看到这里:

您可以在组件中实现 AfterViewChecked,然后在 addUser() 方法中删除 this.userName.nativeElement.focus()

addUser() { 
  this.showInputField = true; 
}

ngAfterViewChecked(): void {
  if (this.showInputField) {
    this.userName.nativeElement.focus();
  }
}

参考:https://stackblitz.com/edit/angular-ycuvth?file=src/app/autocomplete-auto-active-first-option-example.ts