【发布时间】:2019-01-01 19:16:21
【问题描述】:
类似于 Google 登录页面,我希望在点击事件后自动聚焦于输入元素。我已经尝试过@ViewChild('id') 和 document.getElementId('id')。两者都不起作用。它始终为 null 或未定义。我怎样才能做到这一点?
<mat-form-field class="example-full-width col-sm-4">
<input autofocus id="login-username" matInput
formControlName="userName" minlength="5" maxlength="20"
name="userName" placeholder="Username" required #input>
</mat-form-field>
<div class="col-sm-12">
<button (click)="changeView()" type="button" mat-raised-
button color="primary">Next</button>
</div>
<mat-form-field class="example-full-width col-sm-4"
#passwordInput>
<input autofocus type="password" matInput
placeholder="Password" minlength="5" maxlength="20"
formControlName="userPassword" #passwordInput>
</mat-form-field>
【问题讨论】:
-
请显示您在 HTML 中引用 @ViewChild 的一些代码
-
我在构造函数之前声明 @ViewChild('passwordInput') 并在调用时在 changeView() 中使用它。像这样。 changeView(){ this.passwordInputRef.nativeElement.focus();但这会引发错误。说 nativeElement 是未定义的。
-
在 AfterViewInit 生命周期挂钩之前不会设置 ViewChild 属性
-
设置
focus()前需要添加timeout,否则会抛出nativeElementundefined错误
标签: angular html angular-material