javascript - 如何使用 ngIf 将输入的焦点放在表单字段中
问题描述
我面临一个问题,我希望在我的代码中,将重点放在基于可观察数据的条件输入上。在我的示例中,我只是true
在ngOnInit()
.
export class InputOverviewExample implements OnInit {
bool: boolean;
@ViewChild("input1", { static: true }) input1: MatInput;
@ViewChild("input2", { static: true }) input2: MatInput;
ngOnInit() {
this.bool = true;
this.input1.nativeElement.focus();
this.input2.nativeElement.focus();
}
}
mat-form-field
而且我注意到当 a有条件时,焦点不起作用。
<form class="example-form">
<h3>Without *ngIf :</h3>
<mat-form-field appearance="outline" class="example-full-width">
<input matInput #input1 placeholder="Auto focus" value="Test_input1" />
</mat-form-field>
<h3>With *ngIf :</h3>
<mat-form-field appearance="outline" class="example-full-width" *ngIf="bool">
<input matInput #input2 placeholder="Auto focus" value="Test_input2" />
</mat-form-field>
</form>
有人会解决这个问题
谢谢
解决方案
你需要了解 ViewChild {static:true} 和 {static:false} 和 {read}
因此,首先将您的 ViewChild 定义为
@ViewChild("input1", { static: false,read:ElementRef }) input1: ElementRef;
@ViewChild("input2", { static: false,read:ElementRef }) input2: ElementRef;
使static:false
Angular 检查是否在 *ngIf 下
您的read:ElementRef
“input1”和“input2”被视为 ElementRef,而不是 MatInput
您需要的第二件事是 Angular 是如何工作的。Angular 执行所有动作并刷新应用程序,所以如果你写
this.bool = true;
this.input2.nativeElement.focus(); //<--this.input2 is undefined
this.input2 是未定义的,因为 Angular 没有重新绘制应用程序,所以你需要用 setTimeout 括起来 - 你可以像对 Angular 说的那样考虑 setTimeout “嘿,不要忘记刷新应用程序后,你需要再做一个指令” - 或使用ChangeDetectorRef。
所以
ngOnInit() {
this.bool = true;
setTimeout(()=>{
this.input1.nativeElement.focus();
this.input2.nativeElement.focus();
})
}
推荐阅读
- javascript - 如果值为 false,则删除变量
- swift - 如何使用 xmlcoder 解码 xml?
- angular - Rxjs 观察者过滤器不工作错误
- apache-spark - 如何在pyspark的循环中合并数据帧
- sql-server - 使用不同的 Windows 用户帐户登录 SQL Server
- java - 为什么我的 Button 的背景色在运行应用程序时变为灰色?
- javascript - CryptoJS AES 加密到字符串方法和密文到 Base64
- javascript - 带有 javascript 或 php 的 HTML 日志系统
- xcode - 情节提要'未设置指定的入口点'
- tensorflow2.0 - 无法在转换组件 (TFX) 中使用句子嵌入