为了账号安全,请及时绑定邮箱和手机立即绑定

隐藏表单上的 @ViewChild 返回未定义 - 如何访问它以便我可以设置焦点

隐藏表单上的 @ViewChild 返回未定义 - 如何访问它以便我可以设置焦点

肥皂起泡泡 2023-08-10 15:25:14
我有一个只有单击按钮时才可见的表单。我希望用户单击按钮并将焦点放在表单显示后的第一个输入字段上。使用 @Viewchild 我无法执行此操作,因为组件首次加载时表单不可用。我收到错误Cannot read property 'nativeElement' of undefinedTSformLoaded = false;@ViewChild("firstName") nameField: ElementRef;editName(): void { this.formLoaded = true; this.nameField.nativeElement.focus();}超文本标记语言<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 以便为其提供焦点?
查看完整描述

2 回答

?
白衣染霜花

TA贡献1796条经验 获得超10个赞

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

ngAfterViewChecked() {

   if (this.formLoaded) {

      this.nameField.nativeElement.focus();

   }

}

从editName方法中删除 focus 语句:


@ViewChild("firstName") nameField: ElementRef;

editName(): void {

   this.formLoaded = true;

}


查看完整回答
反对 回复 2023-08-10
?
慕码人2483693

TA贡献1860条经验 获得超9个赞

像这样包装焦点方法 isnide settimeout :


 editName(): void {

        this.formLoaded = true;

        setTimeout(()=>{

          this.nameField.nativeElement.focus();

        })

     }

另一种方法是使用 setter


@ViewChild("firstName",{read:MatInput}) set viewC(nameField: MatInput){

 if(nameField){

    nameField.focus();

 }

};

查看完整回答
反对 回复 2023-08-10
  • 2 回答
  • 0 关注
  • 61 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信