Que*_*tin 2 javascript focus typescript angular-material angular
我面临一个问题,我想在我的代码中将重点放在基于可观察数据的条件输入上。在我的示例中,我只是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();
}
}
Run Code Online (Sandbox Code Playgroud)
我注意到当 a 处于条件状态时,焦点不起作用mat-form-field。
<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>
Run Code Online (Sandbox Code Playgroud)
有人会解决这个问题
谢谢
您需要了解 ViewChild {static:true} 和 {static:false} 和 {read}
因此,首先将您的 ViewChild 定义为
@ViewChild("input1", { static: false,read:ElementRef }) input1: ElementRef;
@ViewChild("input2", { static: false,read:ElementRef }) input2: ElementRef;
Run Code Online (Sandbox Code Playgroud)
这static:false使得 Angular 检查是否在 *ngIf 下
这read:ElementRef使得您的“input1”和“input2”被视为 ElementRef,而不是 MatInput
您需要的第二件事是 Angular 的工作原理。Angular 执行所有操作并刷新应用程序,因此如果您编写
this.bool = true;
this.input2.nativeElement.focus(); //<--this.input2 is undefined
Run Code Online (Sandbox Code Playgroud)
this.input2 是未定义的,因为 Angular 没有重新绘制应用程序,所以你需要用 setTimeout 括起来 - 你可以像对 Angular 说的那样思考 setTimeout“嘿,不要忘记刷新应用程序后,你需要再做一个指令” - 或使用ChangeDetectorRef。
所以
ngOnInit() {
this.bool = true;
setTimeout(()=>{
this.input1.nativeElement.focus();
this.input2.nativeElement.focus();
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2344 次 |
| 最近记录: |