首页 > 解决方案 > 如何使用 ngIf 将输入的焦点放在表单字段中

问题描述

我面临一个问题,我希望在我的代码中,将重点放在基于可观察数据的条件输入上。在我的示例中,我只是truengOnInit().

export class InputOverviewExample implements OnInit {
  bool: boolean;

  @ViewChild("input1", { static: true }) input1: MatInput;
  @ViewChild("input2", { static: true }) input2: MatInput;

  ngOnInit() {
    this.bool = true;
    this.input1.nativeElement.focus();
    this.input2.nativeElement.focus();
  }
}

mat-form-field而且我注意到当 a有条件时,焦点不起作用。

<form class="example-form">
  <h3>Without *ngIf :</h3>
  <mat-form-field appearance="outline" class="example-full-width">
    <input matInput #input1 placeholder="Auto focus" value="Test_input1" />
  </mat-form-field>

  <h3>With *ngIf :</h3>
  <mat-form-field appearance="outline" class="example-full-width" *ngIf="bool">
    <input matInput #input2 placeholder="Auto focus" value="Test_input2" />
  </mat-form-field>
</form>

StackBlitz 链接

有人会解决这个问题

谢谢

标签: javascriptangulartypescriptangular-materialfocus

解决方案


你需要了解 ViewChild {static:true} 和 {static:false} 和 {read}

因此,首先将您的 ViewChild 定义为

@ViewChild("input1", { static: false,read:ElementRef }) input1: ElementRef;
@ViewChild("input2", { static: false,read:ElementRef }) input2: ElementRef;

使static:falseAngular 检查是否在 *ngIf 下

您的read:ElementRef“input1”和“input2”被视为 ElementRef,而不是 MatInput

您需要的第二件事是 Angular 是如何工作的。Angular 执行所有动作并刷新应用程序,所以如果你写

this.bool = true;
this.input2.nativeElement.focus(); //<--this.input2 is undefined

this.input2 是未定义的,因为 Angular 没有重新绘制应用程序,所以你需要用 setTimeout 括起来 - 你可以像对 Angular 说的那样考虑 setTimeout “嘿,不要忘记刷新应用程序后,你需要再做一个指令” - 或使用ChangeDetectorRef

所以

  ngOnInit() {
    this.bool = true;
    setTimeout(()=>{
      this.input1.nativeElement.focus();
      this.input2.nativeElement.focus();
    })
  }

推荐阅读