如何专注于Angular中的输入

Dal*_*ley 4 typescript angular

这应该很简单,但是我找不到解决方案,我可以在SO上找到最接近的答案是:我如何以编程方式将焦点设置为Angular2中动态创建的FormControl

但是,这比我的要求更加复杂。我的很简单。我在模板中输入如下:

<div *ngIf="someValue">    
    <input class="form-control" #swiper formControlName="swipe" placeholder="Swipe">
</div>
Run Code Online (Sandbox Code Playgroud)

(请注意,它在ngx-boostrap表单控制组中,但是我敢肯定这应该没关系)

我有一个按钮,当单击该按钮时会调用以下函数:

onClick() {
    this.renderer.invokeElementMethod(this.swiper.nativeElement, 'focus')
}
Run Code Online (Sandbox Code Playgroud)

目的是当单击按钮时,我的输入元素将获得焦点。这是我的其余部分(相关部分):

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

我得到的错误是:

ERROR TypeError: Cannot read property 'focus' of undefined
at RendererAdapter.invokeElementMethod (core.js:12032)
etc...
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

(角度5 btw)

注意,我编辑了代码以更准确地反映实际情况,我认为可能存在一些同步问题。

Dal*_*ley 7

我是这样解决的:

模板:

<input class="form-control" #swiper formControlName="swipe" placeholder="Swipe">
Run Code Online (Sandbox Code Playgroud)

成分:

import { Component, ElementRef, ViewChild } from '@angular/core';

export class MyClass {
    @ViewChild('swiper') swiper: ElementRef;

    constructor() {}

    onClick() {
        this.swiper.nativeElement.focus();
    }
}
Run Code Online (Sandbox Code Playgroud)

关键是两件事:首先使用 ViewChild 而不是 ViewChildren(感谢@Teddy Stern),其次根本不需要使用渲染器,只需直接使用 nativeElement 的焦点功能。


Ted*_*rne 6

您正在使用ViewChildren哪个返回值,QueryList您需要使用ViewChild,您的代码应该可以正常工作。

export class MyClass {
    @ViewChild('swiper') swiper: ElementRef;

    constructor(private renderer: Renderer) {}

    onClick() {
        this.swiper.nativeElement.focus();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我收到错误 @ViewChild() 错误:需要 2 个参数,但得到 1。通过添加 {static:false} 解决,即:`@ViewChild('swiper', {static: false}) swiper: ElementRef;` (2认同)