当ngIf变为true时,触发功能将焦点设置为显示的输入

问题描述 投票:1回答:4

我目前正在尝试将光标集中在特定的输入字段上,该字段仅在周围的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并且输入可见后,如何将焦点设置在输入字段上?

javascript angular
4个回答
1
投票

您可以在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;
  }
}

0
投票

您可以使用autofocus属性。或者,如果showFirst为false,则在(单击)结尾处添加setFocus


0
投票

您可以尝试在OnChanges生命周期钩子中获取ElementRef。就像是:

OnChanges(): void {
  if (!this.showFirst) {
    // check ElementRef
  }
}

0
投票

Angular有一个生命周期钩子ngAfterViewChecked,它在每次检查组件视图后调用。

一旦你的视图被更改,将调用这个生命周期钩子,在这里你可以编写聚焦逻辑。

ngAfterViewChecked(){
  // you logic for focusing or check ElementRef.
}
© www.soinside.com 2019 - 2024. All rights reserved.