【问题标题】:Angular - Focus on input element that has ngIfAngular - 专注于具有 ngIf 的输入元素
【发布时间】:2019-06-24 05:53:16
【问题描述】:

我有两个在*ngIf 条件下显示的输入元素。

<input type="text" id="textInput" *ngIf="showTextInput">
<input type="number" id="numericInput" *ngIf="showNumericInput">

<button (click)="editButtonClicked($event)">

单击按钮应将焦点设置到相应的输入元素。

editButtonClicked(event) {
  // Focus on either #textInput or #numericInput element
}

我已经查看了 ElementRef 以提供 html 输入元素标签,例如 #textInput,然后在类中定义它们,例如:

@ViewChild('textInput') textInput: ElementRef;

...但显然这不适用于具有*ngIf 条件的元素。

如何在点击按钮时关注输入元素?

【问题讨论】:

  • @ViewChild in *ngIf的可能重复
  • 您想在按钮单击时将焦点设置在textInput 上吗?
  • 对 ElementRef 使用一些超时,希望对您有所帮助。
  • @PrashantPimpale 正确,我想在按钮单击时将焦点设置在 textInput
  • @bruh 您尝试过发布答案吗?这有帮助吗?

标签: javascript html angular


【解决方案1】:

您可以实现一个超级简单的指令并获得所需的效果。

html

<input type="text" autoFocus *ngIf="isInputVisible">

指令

import { Directive, ElementRef, OnInit } from "@angular/core";

@Directive({
  selector: "[autoFocus]"
})
export class AutoFocusDirective implements OnInit {
  private inputElement: HTMLElement;

  constructor(private elementRef: ElementRef) {
    this.inputElement = this.elementRef.nativeElement;
  }

  ngOnInit(): void {
    this.inputElement.focus();
  }
}

工作演示:

https://stackblitz.com/edit/angular-ivy-vvgcch?file=src%2Fapp%2Fdirectives%2Fauto-focus.directive.ts

【讨论】:

    【解决方案2】:

    是的@ViewChild 不适用于受结构指令控制的元素。您可以应用两种解决方法:

    1. 移除 *ngIf 指令并使用 CSS style: 'display:none' 隐藏元素。

    2. 使用 vanilla Javascript document.getElementById('someId'); 从 DOM 中选择元素,然后聚焦该元素。

    我更喜欢第 1 点。

    【讨论】:

      【解决方案3】:

      如果您正在寻找模板引用变量,您也可以这样做

      在 html 中

      <input #text type="text" id="textInput">
      <input #number type="number" id="numericInput">
      
      <button (click)="editButtonClicked($event, text, number)"> Click </button>
      

      在ts中

      editButtonClicked(e, text, number){
          if(text.value) {
            text.focus()
          } else {
            number.focus()
          }
        }
      

      【讨论】:

      • Usman,由于输入在 *ngIf 下,您需要更改变量的值,并在 setTimeout 中获得焦点 - setTimeout 需要让 Angular 有时间显示元素 -
      • 感谢您的回复,正如 Eliseo 所提到的 - 由于 *ngIf 条件,此解决方案需要类似 setTimeout 的东西。我认为setTimeout() 是一个相当老套的解决方案,所以我会避免这种情况。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 2015-07-30
      相关资源
      最近更新 更多