如何在Angular 6中手动将焦点设置在mat-form-field上

时间:2018-09-03 04:11:46

标签: angular typescript angular-material

我是angular的新手,在我的应用程序中,我有一个Mat-dialog,其中有两种形式,分别是Login和SignUp。

第一次打开对话框时,将自动焦点设置在用户名字段上。问题是当我单击按钮导航至“注册表单”时,表单的“名字”字段未自动聚焦,这与从注册导航到登录用户名的方式相同字段现在不会自动聚焦。

我已经尝试了一些stackoverflow解决方案,但没有任何解决方案解决我的问题。

popupScreen.component.html

<form class="login" *ngIf="isLoginHide">
    <mat-form-field>
        <input matInput placeholder="username">
    </mat-form-field>
    <mat-form-field>
        <input matInput placeholder="password">
    </mat-form-field>

    <button mat-button color="primary">Login</button>
    <button mat-button (click)="hideLogin($event)" color="accent">SignUp</button>
</form>

<form class="SignUp" *ngIf="isSignUpHide">
    <mat-form-field>
        <input matInput placeholder="First Name">
    </mat-form-field>
    <mat-form-field>
        <input matInput placeholder="Last Name">
    </mat-form-field>
    <mat-form-field>
        <input matInput placeholder="username">
    </mat-form-field>
    <mat-form-field>
        <input matInput placeholder="password">
    </mat-form-field>

    <button mat-button (click)="hideSignUp($event)" color="primary">Login</button>
    <button mat-button color="accent">SignUp</button>
</form>

谁能帮我解决这个问题。

10 个答案:

答案 0 :(得分:4)

您可以使用 MatInput 设置自动对焦

这是一个例子,

component.html

<mat-form-field>
    <input matInput placeholder="First Name" #firstname="matInput">
</mat-form-field>

component.ts

import { MatInput } from '@angular/material/input';

export class Component implements OnInit {

    @ViewChild('firstname') nameInput: MatInput;

    ngOnInit() {
       this.nameInput.focus();
    }
}

答案 1 :(得分:3)

这对我有用:

<mat-label >Radio name:</mat-label>
   <input type="text" #inputName="matInput" matInput formControlName="name" placeholder="Type radio name"/>
</mat-form-field>

  @ViewChild('inputName', { static: false }) inputName: MatInput;

  ngAfterViewInit(): void {
    setTimeout(() => this.inputName.focus(), 0);
  }

setTimeout 是一种避免变更检测问题的黑客。我不知道为什么,但手动执行更改检测在我的情况下不起作用。

答案 2 :(得分:2)

请在要聚焦的输入字段中使用“ cdkFocusInitial”属性。

var a = "sample data"
const returnDataOfLet = (a) => {
switch(typeof a){
    case "string": 
      let a = a.split(" ") // will throw an error change let to var it will work
      return a 
}
}

console.log(returnDataOfLet(a))

答案 3 :(得分:1)

使用可以使用本机元素的焦点。

尚未测试此代码,但是类似以下内容:

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

在您的组件上:

@ViewChild('usernameInput') usrFld: ElementRef;

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

p.s:您应该路由到注册组件,而不要使用ngIf进行导航。

答案 4 :(得分:1)

您是否尝试过将autofocus添加到名字的表单字段中?

<form class="SignUp" *ngIf="isSignUpHide">
    <mat-form-field>
        <input matInput placeholder="First Name" autofocus>
    </mat-form-field>
    <mat-form-field>
        <input matInput placeholder="Last Name">
    </mat-form-field>
    <mat-form-field>
        <input matInput placeholder="username">
    </mat-form-field>
    <mat-form-field>
        <input matInput placeholder="password">
    </mat-form-field>

    <button mat-button (click)="hideSignUp($event)" color="primary">Login</button>
    <button mat-button color="accent">SignUp</button>
</form>

答案 5 :(得分:1)

几乎.. :-),如果您使用的是MatSelect之类的材料组件,上述解决方案将不起作用。您可以在下面找到适合我的解决方案。

<mat-form-field>
    <mat-select #myElement ......>
       ..........
    </mat-select>
<mat-form-field>

然后在组件中...

@ViewChild('myElement') firstItem: MatSelect;

ngAfterViewInit() {
   this.firstItem.focus();
   this.cd.detectChanges();
}

请记住,您必须在设置焦点后强制进行更改检测,以避免Angular错误:“ ExpressionChangedAfterItHaHasBeenCheckedError ”(顺便说一句,您还必须在其中包含“ ChangeDetectorRef ”组件构造函数)

希望获得帮助...

答案 6 :(得分:1)

这在Angular 8中对我有效:

<mat-form-field>
    <input matInput placeholder="First Name" #firstname>
</mat-form-field>

.ts

export class TestComponent implements OnInit {

    @ViewChild('firstname', {static: true}) firstname:any;

    ngOnInit() {
      this.firstname.nativeElement.focus();
    }

}

答案 7 :(得分:0)

请注意,根据显示组件的时间和方式,ngOnInit可能不是设置焦点的地方。

例如,如果ComponentOne的html看起来像这样:

  <ng-container *ngIf='something === true'>
    <app-component-two></app-component-two>
  </ng-container>

然后ComponentTwo具有您的输入元素,并且ComponentTwo的ts文件已正确设置,然后将其放入您的component-two.component.ts文件中:

ngOnInit() {
  this.myInput.focus();
}

可能不起作用,因为尚未呈现ComponentTwo的html,这意味着即使正确使用了ViewChild,this.myInput也不会呈现并且为空。

ngAfterViewInit() {
  this.myInput.focus();
}

即使您不嵌套组件,也可能仍需要注意html的生命周期,以确保您的focus命令在呈现输入元素之后发生。

请查看https://angular.io/guide/lifecycle-hooks#lifecycle-event-sequence,以获取有关角度生命周期的更多信息。

答案 8 :(得分:0)

对于 MatDialog ,您将不得不通过 setTimeout

延迟操作
<mat-form-field>
  <mat-label>Name</mat-label>
  <input #inputName="matInput" matInput formControlName="name">
</mat-form-field>

@ViewChild('inputName') inputName: MatInput;

ngAfterViewInit() {
  setTimeout(() => {
    this.inputName.focus();
  });
}

答案 9 :(得分:0)

这么简单而普通的事情,但上面的大部分内容对我都不起作用。

cdkFocusInitial 效果很好,除非您使用步进器控件或等效控件,希望新输入集中在 stepper.next() 上。

我最终没有使用 viewchild 来获取对对象的引用,而是使用了老式的 id。

public setFocus(input: string) {
   const targetElem = document.getElementById(input);
   setTimeout(function waitTargetElem() {
    if (document.body.contains(targetElem)) {
      targetElem.focus();
    } else {
      setTimeout(waitTargetElem, 100);
    }
  }, 500);
}

用...调用它

this.setfocus('id of your input')