我目前正在尝试将光标集中在特定的输入字段上,该字段仅在周围的ngIf为真时显示。 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,但它一直返回undefined
,因为我尝试在初始化之前获取它。
所以qustion是:
在showFirst
变为false
并且输入可见后,如何将焦点设置在输入字段上?
您可以在AfterViewChecked
生命周期钩子中设置焦点,如this plunker所示。我添加了一个检查以确保仅在输入元素变为可见时才设置焦点,而不是每次触发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;
}
}
您可以使用autofocus属性。或者,如果showFirst为false,则在(单击)结尾处添加setFocus
您可以尝试在OnChanges生命周期钩子中获取ElementRef。就像是:
OnChanges(): void {
if (!this.showFirst) {
// check ElementRef
}
}
Angular有一个生命周期钩子ngAfterViewChecked
,它在每次检查组件视图后调用。
一旦你的视图被更改,将调用这个生命周期钩子,在这里你可以编写聚焦逻辑。
ngAfterViewChecked(){
// you logic for focusing or check ElementRef.
}