如何专注于Angular中的输入 [英] how to focus on an input in Angular
问题描述
这应该很简单,但是我找不到解决方案,因此我可以在SO上找到最接近的答案是:
This should be simple but I can't find a solution, the closest answer i can find on SO is this: How do I programmatically set focus to dynamically created FormControl in Angular2
但是,这比我的要求更复杂.我的很简单.我在模板中输入如下:
However this is way more convoluted that my requirements. Mine are simple. I have an input in the template like so:
<div *ngIf="someValue">
<input class="form-control" #swiper formControlName="swipe" placeholder="Swipe">
</div>
(注意,它在ngx-boostrap表单控制组中,但是我敢肯定这应该没关系)
(Note, it's in an ngx-boostrap form-control group but I'm pretty sure this should not matter)
我有一个按钮,当单击该按钮时,它将调用以下函数:
And I have a button that when clicked calls the following function:
onClick() {
this.renderer.invokeElementMethod(this.swiper.nativeElement, 'focus')
}
目标是当单击按钮时,我的输入元素将获得焦点.这是我的其余部分(相关部分):
The goal is that when the button is clicked, my input element gets focus. here is the rest of my component (the relevant parts):
import { Component, ElementRef, ViewChildren, Renderer } from '@angular/core';
import { MyService } from wherever/my/service/is
export class MyClass {
@ViewChildren('swiper') input: ElementRef;
someValue: any = false;
constructor(private renderer: Renderer, service: MyService) {
this.service.getSomeData().subscribe(data => {
this.someValue = true;
}
}
onClick() {
this.renderer.invokeElementMethod(this.swiper.nativeElement, 'focus');
}
}
我得到的错误是:
ERROR TypeError: Cannot read property 'focus' of undefined
at RendererAdapter.invokeElementMethod (core.js:12032)
etc...
有什么想法吗?
(角度5 btw)
请注意,我编辑了代码以更准确地反映实际情况,我认为可能存在一些同步问题.
Note, I edited the code to more accurately reflect what is actually going on, I think there may be some synchronization issue.
推荐答案
您正在使用ViewChildren
,它返回一个QueryList
您需要使用ViewChild
并且您的代码应该可以工作.
You are using ViewChildren
which returns a QueryList
You need to use ViewChild
and your code should work.
export class MyClass {
@ViewChild('swiper') swiper: ElementRef;
constructor(private renderer: Renderer) {}
onClick() {
this.swiper.nativeElement.focus();
}
}
这篇关于如何专注于Angular中的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!