@ViewChild on hidden form returns undefined - 如何访问它以便我可以设置焦点

@ViewChild on hidden form returns undefined - How to access it so I can set a focus

我有一个只有在单击按钮时才可见的表单。我希望用户单击按钮,并在显示表单后将焦点放在第一个输入字段上。

使用@Viewchild 我无法做到这一点,因为当组件首次加载时表单不可用。我收到错误 Cannot read property 'nativeElement' of undefined

TS

formLoaded = false;

@ViewChild("firstName") nameField: ElementRef;
editName(): void {
 this.formLoaded = true;
 this.nameField.nativeElement.focus();
}

HTML

<button mat-raised-button color="primary" (click)="editName()">Edit</button>
 <div *ngIf="formLoaded" class="group">
  <mat-form-field>
   <input #firstName matInput>
  </mat-form-field>
</div>

如何访问输入 #firstName 以便为其赋予焦点?

我的实际代码的简化版本是 here

像这样在 settimeout 中包装 focus 方法:

 editName(): void {
        this.formLoaded = true;
        setTimeout(()=>{
          this.nameField.nativeElement.focus();
        })
     }

另一种方法是使用setter

@ViewChild("firstName",{read:MatInput}) set viewC(nameField: MatInput){
 if(nameField){
    nameField.focus();
 }
};

Forked Example

利用 AfterViewChecked 生命周期挂钩,它是 运行 每次触发变更检测。因此,只有在表单出现在模板上后,您才会为其设置焦点。

ngAfterViewChecked() {
   if (this.formLoaded) {
      this.nameField.nativeElement.focus();
   }
}

editName 方法中删除焦点语句:

@ViewChild("firstName") nameField: ElementRef;
editName(): void {
   this.formLoaded = true;
}