我有一个只有单击按钮时才可见的表单。我希望用户单击按钮并将焦点放在表单显示后的第一个输入字段上。
使用 @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 以便为其提供焦点?
白衣染霜花
慕码人2483693
相关分类