我有两个输入元素,它们在*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,给出了像#textInput这样的html输入元素标记,然后在类中定义它们,例如:
@ViewChild('textInput') textInput: ElementRef;...but显然不适用于具有*ngIf条件的元素。
如何专注于输入元素,按钮的onClick?
发布于 2021-01-15 18:01:11
您可以实现一个超级简单的指令,并具有所需的效果。
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
发布于 2019-06-24 06:09:43
是的,@ViewChild不适用于结构指令控制下的元素。有两个解决办法可供您应用:
*ngIf指令并使用CSS style: 'display:none'隐藏元素。document.getElementById('someId');从DOM中选择元素,然后对元素进行对焦。我更喜欢第1点。
发布于 2019-06-24 06:30:56
如果您正在寻找模板引用变量,也可以通过模板引用变量进行此操作。
中的html
<input #text type="text" id="textInput">
<input #number type="number" id="numericInput">
<button (click)="editButtonClicked($event, text, number)"> Click </button>in ts
editButtonClicked(e, text, number){
if(text.value) {
text.focus()
} else {
number.focus()
}
}https://stackoverflow.com/questions/56730540
复制相似问题