角度-专注于具有ngIf的输入元素

时间:2019-06-24 05:53:16

标签: javascript html angular

我有两个在(->> (str n) seq (map (comp read-string str))) 条件下显示的输入元素。

*ngIf

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

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

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

我研究了 ElementRef ,以提供html输入元素标签,例如editButtonClicked(event) { // Focus on either #textInput or #numericInput element } ,然后在类中定义它们,例如:

#textInput

...但是显然,这不适用于具有@ViewChild('textInput') textInput: ElementRef; 条件的元素。

我如何专注于输入元素,即单击按钮?

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

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

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

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

我更喜欢第1点。

答案 2 :(得分:1)

如果您正在寻找的话,也可以通过模板引用变量来完成此操作

以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()
    }
  }
相关问题