Angular - 关注具有 ngIf 的输入元素

bru*_*ruh 3 html javascript angular

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

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

<button (click)="editButtonClicked($event)">
Run Code Online (Sandbox Code Playgroud)

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

editButtonClicked(event) {
  // Focus on either #textInput or #numericInput element
}
Run Code Online (Sandbox Code Playgroud)

我研究了ElementRef来给出 html 输入元素标签,#textInput然后在类上定义它们,例如:

@ViewChild('textInput') textInput: ElementRef;
Run Code Online (Sandbox Code Playgroud)

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

如何聚焦于输入元素、按钮的 onClick?

小智 8

您可以实现一个超级简单的指令并达到预期的效果。

html

<input type="text" autoFocus *ngIf="isInputVisible">
Run Code Online (Sandbox Code Playgroud)

指示

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

工作演示:

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