简体   繁体   English

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

[英]Autofocus on an input field on button click in angular 9

I have add buttons at two separate places inside my component.我在组件内的两个不同位置添加了按钮。 On click of the button, the input field shows up.单击该按钮后,将显示输入字段。 I have tried multiple ways to achieve this as follows:我尝试了多种方法来实现这一点,如下所示:

Used autofocus attribute on the input field - as i have two buttons on the screen, autofocus does not seem to work.在输入字段上使用了自动对焦属性- 因为我在屏幕上有两个按钮,所以自动对焦似乎不起作用。

Used .用过的 。 focus () method -焦点()方法 -

HTML File HTML文件

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

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

TS File TS文件

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

In second case, i got the error "cannot read the property nativeElement of undefined", which is because the HTML loads after the execution of method completes.在第二种情况下,我收到错误“无法读取未定义的属性 nativeElement”,这是因为在方法执行完成后加载了 HTML。

You can implement AfterViewChecked in your component and then just remove that this.userName.nativeElement.focus() in addUser() method.您可以实现AfterViewChecked在您的组件,然后只是删除this.userName.nativeElement.focus()addUser()方法。

addUser() { 
  this.showInputField = true; 
}

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

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

It's probably not the best solution but you can use setTimeout() to wait for the boolean value to change.这可能不是最好的解决方案,但您可以使用setTimeout()等待布尔值更改。

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

Seen here : https://stackoverflow.com/a/50014475/6444705在这里看到: https : //stackoverflow.com/a/50014475/6444705

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM