How to set autofocus on a matInput element on click event in Angular 6?

时间:2018-07-25 04:42:27

标签: angular html5 angular-material

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>

5 个答案:

答案 0 :(得分:4)

If you want to set focus to an Input field as soon as the page loads, you can do it simply by applying HTML attribute to that element, such as :

<input type="text" #input1 autofocus>

Else if you want to do this from your component.ts conditionally, use:

    import { Component, ElementRef, ViewChild, AfterViewInit} from 
    '@angular/core';
    ... 

 @ViewChild('input1') inputEl:ElementRef;

 ngAfterViewInit() {
 this.inputEl.nativeElement.focus();
 }

Or you can use:

First import the renderer2 from @angular/core and then,

    const element = this.renderer.selectRootElement('#input1');

 setTimeout(() => element.focus(), 0);

Whatever you seems to be comfortable with your existing code.

答案 1 :(得分:3)

使用Angular Material时,可以使用cdkFocusInitial告诉库在组件准备好后要聚焦的位置。不需要本机方法:

<mat-form-field class="example-full-width">
  <mat-label>My Label</mat-label>
  <textarea 
    cdkFocusInitial           <---------
    cdkTextareaAutosize
    matInput>
  </textarea>
</mat-form-field>

答案 2 :(得分:1)

您可以使用Material中的cdkFocusInitial

<mat-form-field>
    <input matInput placeholder="username" cdkFocusInitial>
</mat-form-field>

请参见orginal答案。

答案 3 :(得分:0)

You need to use template ref to input element then use ViewChild it will work

Example: https://stackblitz.com/edit/angular-frqm8b

 <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" 
          >
        <input autofocus type="password" matInput 
        ****#passwordInput****
       placeholder="Password" minlength="5" maxlength="20" 
       formControlName="userPassword" #passwordInput>  
      </mat-form-field>

答案 4 :(得分:0)

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

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

相反,应该调用matInput.focus()。这是使用此方法的简单指令:

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在创建时仍无法正常运行。用法:

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

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