本文介绍了如何在Angular 6中的click事件上对matInput元素设置自动对焦?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于Google登录页面,我希望点击事件后自动聚焦于输入元素.我尝试了@ViewChild('id')和document.getElementId('id').两者都不起作用.它始终为null或未定义.我该如何实现?

Similar to Google Login page, I want to have autofocus on input element after on click event. I have tried @ViewChild('id') and document.getElementId('id'). Both of it doesn't work. It's always null or undefined. How can I achieve this?

       <mat-form-field class="example-full-width col-sm-4">
        <input autofocus id="login-username" matInput 
       formControlName="userName" minlength="5" maxlength="20" 
       name="userName" placeholder="Username" required #input> 
      </mat-form-field>

        <div class="col-sm-12">
           <button (click)="changeView()" type="button" mat-raised-
             button color="primary">Next</button>
          </div>

         <mat-form-field class="example-full-width col-sm-4" 
          #passwordInput>
        <input autofocus type="password" matInput 
       placeholder="Password" minlength="5" maxlength="20" 
       formControlName="userPassword" #passwordInput>  
      </mat-form-field>

推荐答案

不幸的是,所有其他解决方案在渲染时不适用于自动对焦的matInput.

Unfortunately all other solutions do not work with autofocusing matInput at the moment of rendering.

原因是,人们应该使用matInput的高级api,而不是尝试着眼于输入本身.

The reason is that one should use a high-level api of the matInput instead of attempting to focus the input itself.

应该执行的是调用matInput.focus().这是使用此方法的简单指令:

What should be done instead is calling matInput.focus(). Here is a simple directive that uses this approach:

import { Directive, OnInit } from '@angular/core';
import { MatInput } from '@angular/material';

@Directive({
  selector: '[matInputAutofocus]',
})
export class AutofocusDirective implements OnInit {

  constructor(private matInput: MatInput) { }

  ngOnInit() {
    setTimeout(() => this.matInput.focus());
  }

}

需要超时才能延迟对元素的聚焦,因为matInput在创建时仍无法正常运行.用法:

The timeout is required to delay focusing the element because matInput does not properly function at the moment of creating yet. Usage:

<mat-form-field>
  <input type="text" matInput matInputAutofocus>
</mat-form-field>

当然,为选择器matInputAutofocus命名是很危险的,因为材料本身可能有一天会出现在此解决方案中.使用它需要您自担风险,或仅使用前缀重命名(推荐).

Of course, naming the selector matInputAutofocus is dangerous because material itself can come to this solution one day. Use it on your own risk or just rename with your prefix (recommended).

这篇关于如何在Angular 6中的click事件上对matInput元素设置自动对焦?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 01:42