Javascript ngIf为真时触发函数,将焦点设置在显示的输入上
我目前正试图将光标的焦点设置在一个特定的输入字段上,当周围的ngIf为true时,该字段才显示出来。Javascript ngIf为真时触发函数,将焦点设置在显示的输入上,javascript,angular,Javascript,Angular,我目前正试图将光标的焦点设置在一个特定的输入字段上,当周围的ngIf为true时,该字段才显示出来。 html代码如下所示: <div> <button (click)="showFirst = !showFirst">Toogle</button> <div *ngIf="showFirst"> <!-- Some content --> </div> <div *ng
html代码如下所示:
<div>
<button (click)="showFirst = !showFirst">Toogle</button>
<div *ngIf="showFirst">
<!-- Some content -->
</div>
<div *ngIf="!showFirst">
<input type="text" #myInput>
</div>
</div>
图格尔
在我的组件JS中,我试图获取ElementRef,但它始终返回未定义的
,因为我试图在初始化它之前获取它。所以问题是:
在
showFirst
变为false
且输入可见后,如何在输入字段上设置焦点?您可以使用自动聚焦属性。
或者只需在(单击)的末尾添加一个setFocus,如果showFirst为false,您可以尝试在OnChanges生命周期挂钩中获取ElementRef。比如:
OnChanges(): void {
if (!this.showFirst) {
// check ElementRef
}
}
Angular有一个lifecycle钩子
nAfterViewChecked
,它在每次检查组件视图后调用
一旦您的视图被更改,这个生命周期钩子将被调用,在这里您可以编写聚焦的逻辑
ngAfterViewChecked(){
// you logic for focusing or check ElementRef.
}
您可以在
AfterViewChecked
lifecycle挂钩中设置焦点,如中所示。我添加了一个检查,以确保焦点仅在输入元素可见时设置,而不是每次触发AfterViewChecked
时设置
import { Component, ViewChild, AfterViewChecked, ElementRef } from '@angular/core';
export class MyComponent implements AfterViewChecked {
@ViewChild("myInput") private myInput: ElementRef;
public showFirst = true;
private prevShowFirst = true;
public ngAfterViewChecked(): void {
if (!this.showFirst && this.prevShowFirst) {
this.myInput.nativeElement.focus();
}
this.prevShowFirst = this.showFirst;
}
}