如何在 Angular 6 中的单击事件上对 matInput 元素设置自动对焦? [英] How to set autofocus on a matInput element on click event in Angular 6?

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

问题描述

类似于 Google 登录页面,我希望在点击事件后自动聚焦输入元素.我试过@ViewChild('id') 和 document.getElementId('id').两者都不起作用.它始终为空或未定义.我怎样才能做到这一点?

 <input autofocus id="login-username" matInputformControlName="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">下一步</button>

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

解决方案

不幸的是,并非每个解决方案都在渲染时始终使用自动对焦 matInput.这是我尝试过的:

  • HTML autofocus 属性
  • JS input.focus()
  • cdkFocusInitial 来自 @angular/cdk

上述所有方法都可能有效,但在某些情况下它们似乎已失效.

一贯始终的工作原理是使用matInput的高级API.这是一个使用这种方法的简单指令:

import { Directive, OnInit } from '@angular/core';从'@angular/material/input' 导入 { MatInput };@指示({选择器:'[matInputAutofocus]',})导出类 AutofocusDirective 实现 OnInit {构造函数(私有 matInput:MatInput){}ngOnInit() {setTimeout(() => this.matInput.focus());}}

需要超时来延迟元素聚焦,因为 matInput 在创建时尚未正常运行.用法:

<输入类型=文本"matInput matInputAutofocus></mat-form-field>

当然,将选择器命名为 matInputAutofocus 是危险的,因为材料本身有一天会出现这种解决方案.使用它的风险由您自己承担,或者只是使用您的前缀重命名(推荐).

对焦并同时选择输入值

锦上添花的是增加了预先选择输入内容的可能性(这在大多数情况下对用户更友好),这稍微改变了实现:

import { Directive, OnInit } from '@angular/core';从'@angular/material/input' 导入 { MatInput };@指示({选择器:'[matInputAutofocus]',})导出类 AutofocusDirective 实现 OnInit {@输入()autofocusSelectValue = false;构造函数(私人垫输入:垫输入,私有 elRef: ElementRef,) { }ngOnInit(): 无效 {setTimeout(() => {this.matInput.focus();如果(this.autofocusSelectValue){this.elRef.nativeElement.setSelectionRange(0, input.value.length);}});}}

将其用作:

<输入类型=文本"matInput matInputAutofocus [autofocusSelectValue]=true"></mat-form-field>

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>

解决方案

Unfortunately not every solution consistently works with autofocusing matInput at the moment of rendering. Here is what I tried:

  • HTML autofocus attribute
  • JS input.focus()
  • cdkFocusInitial from @angular/cdk

All of the above methods might work but under some conditions they appear to be broken.

What consistently and always works is using a high-level api of the matInput. Here is a simple directive that uses this approach:

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

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

  constructor(private matInput: MatInput) { }

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

}

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>

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).

Focus and meanwhile select the input value

A cherry on the cake is adding the possibility to also preselect the content of the input (this is most of the time more user-friendly), which slightly changes the implementation:

import { Directive, OnInit } from '@angular/core';
import { MatInput } from '@angular/material/input';
    
@Directive({
  selector: '[matInputAutofocus]',
})
export class AutofocusDirective implements OnInit {

  @Input()
  autofocusSelectValue = false;

  constructor(
    private matInput: MatInput,
    private elRef: ElementRef<HTMLInputElement>,
  ) { }

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

      if (this.autofocusSelectValue) {
        this.elRef.nativeElement.setSelectionRange(0, input.value.length);
      }
    });
  }

}

Use it as:

<mat-form-field>
  <input type="text" matInput matInputAutofocus [autofocusSelectValue]="true">
</mat-form-field>

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆