- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我遇到了一个问题,我想在我的代码中将焦点放在条件输入上基于可观察的数据。在我的示例中,我只是在 ngOnInit()
中将 bool 值设置为 true
。
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
被调节时焦点不起作用。
<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 - 如何使用 ngIf 将输入的焦点放在表单字段中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64495986/
我尝试通过正则表达式将文本中的单引号更改为双引号。 (单字)示例:我走了。 You gona fly to planet 'Ziqtos' => 我需要在 I'm 中保留单引号,并在 You gona
我正在构建一个 API,其中大部分将包含 JSON 和 HTML 内容。但是一些非常具体的端点只呈现 true 或 false,并且还在 POST 中接受 true 或 false。这是请求或响应的整
我是一名优秀的程序员,十分优秀!