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

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


使用 @Viewchild 我无法执行此操作,因为组件首次加载时表单不可用。我收到错误Cannot read property 'nativeElement' of undefined


TS


formLoaded = 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 以便为其提供焦点?



肥皂起泡泡
浏览 63回答 2
2回答

白衣染霜花

利用AfterViewChecked生命周期挂钩,每次触发更改检测时都会运行它。因此,只有在表单出现在模板上之后,您才能为其设置焦点。ngAfterViewChecked() {   if (this.formLoaded) {      this.nameField.nativeElement.focus();   }}从editName方法中删除 focus 语句:@ViewChild("firstName") nameField: ElementRef;editName(): void {   this.formLoaded = true;}

慕码人2483693

像这样包装焦点方法 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(); }};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript