【问题标题】:Autofocus on an input field on button click in angular 9在角度 9 中单击按钮时自动聚焦在输入字段上
【发布时间】:2020-11-17 09:17:16
【问题描述】:

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

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

使用 .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 在方法执行完成后加载。

【问题讨论】:

    标签: angular autofocus


    【解决方案1】:

    您可以在组件中实现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

    【讨论】:

    • 感谢您的快速回复,该解决方案似乎有效,但在使用此生命周期挂钩后,我在控制台中出现错误“错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。' 的先前值mat-form-field-should-float': 'false'。当前值:'true'。"
    • 您是否尝试过我在上面的 stackblitz url 中提供的内容?
    • 是的,我使用了完全相同的代码,但是使用这个link,我摆脱了上述错误,发布后我得到了 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked . 'mat-focused' 的先前值:'false'。当前值:“真”。
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-14
      • 2012-09-08
      • 2020-01-04
      • 1970-01-01
      相关资源
      最近更新 更多