简体   繁体   English

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

[英]Angular - Focus on input element that has ngIf

I have two input elements that are shown under *ngIf conditions.我有两个在*ngIf条件下显示的输入元素。

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

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

Clicking on the button should set focus to the appropriate input element.单击按钮应将焦点设置为适当的输入元素。

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

I've looked into ElementRef to give the html input elements tags like #textInput and then define them on the class for example:我已经研究了ElementRef以提供 html 输入元素标签,例如#textInput然后在类上定义它们,例如:

@ViewChild('textInput') textInput: ElementRef;

...but apparently this does not work on elements that have *ngIf conditionals. ...但显然这不适用于具有*ngIf条件的元素。

How can I focus on an input element, onClick of a button?我怎样才能专注于一个输入元素,一个按钮的点击?

You could implement a super simple directive and have the desired effect.您可以实现一个超级简单的指令并获得所需的效果。

html html

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

directive指示

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();
  }
}

Working Demo:工作演示:

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

Yes @ViewChild will not work for elements who are under the control of a structural directive.是的@ViewChild不适用于受结构指令控制的元素。 There are two workaround that you can apply:您可以应用两种解决方法:

  1. Remove the *ngIf directive and hide the element using CSS style: 'display:none' .删除*ngIf指令并使用 CSS style: 'display:none'隐藏元素style: 'display:none'

  2. Select the element from the DOM using vanilla Javascript document.getElementById('someId');使用 vanilla Javascript document.getElementById('someId');从 DOM 中选择元素document.getElementById('someId'); and then focus the element.然后聚焦元素。

I will prefer point 1.我更喜欢第 1 点。

you can also do this by template reference variable if that's what you are looking for如果这是您要查找的内容,您也可以通过模板引用变量来执行此操作

in html在 html 中

<input #text type="text" id="textInput">
<input #number type="number" id="numericInput">

<button (click)="editButtonClicked($event, text, number)"> Click </button>

in ts在 ts

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM