簡體   English   中英

如何專注於 Angular 中的輸入

[英]how to focus on an input in Angular

這應該很簡單,但我找不到解決方案,我能在 SO 上找到的最接近的答案是: 如何以編程方式將焦點設置為在 Angular2 中動態創建的 FormControl

然而,這比我的要求更復雜。 我的很簡單。 我在模板中有一個輸入,如下所示:

<div *ngIf="someValue">    
    <input class="form-control" #swiper formControlName="swipe" placeholder="Swipe">
</div>

(注意,它在 ngx-boostrap form-control 組中,但我很確定這無關緊要)

我有一個按鈕,單擊時調用以下函數:

onClick() {
    this.renderer.invokeElementMethod(this.swiper.nativeElement, 'focus')
}

目標是當按鈕被點擊時,我的輸入元素獲得焦點。 這是我的組件的其余部分(相關部分):

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)

請注意,我編輯了代碼以更准確地反映實際情況,我認為可能存在一些同步問題。

您正在使用ViewChildren它返回一個QueryList你需要使用ViewChild和你的代碼應該工作。

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

    constructor(private renderer: Renderer) {}

    onClick() {
        this.swiper.nativeElement.focus();
    }
}

我是這樣解決的:

模板:

<input class="form-control" #swiper formControlName="swipe" placeholder="Swipe">

組件:

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

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

    constructor() {}

    onClick() {
        this.swiper.nativeElement.focus();
    }
}

關鍵是兩件事:首先使用 ViewChild 而不是 ViewChildren(感謝@Teddy Stern),其次根本不需要使用渲染器,只需直接使用 nativeElement 的焦點功能。

如果你有一個輸入和一個按鈕

<input #myinput>
<button (click)="myinput.focus()">click</button>

如果有人感興趣,為了關注動態生成的元素, #name不可能作為屬性保留在字段中。 我找到了一種使用原生 JS 的方法。

<textarea [(ngModel)]="update.newComment"
          [name]="'update-' + index" 
          placeholder="comment"></textarea>

現在,專注於上面textarea的觸發器可能就像

<span (click)="focusOn(index);">Comment</span>

單擊事件將在 ts 中處理為

focusOn(fieldName) {
    const commmentBoxes = document.querySelectorAll(`textarea[ng-reflect-name="update-${fieldName}"]`);
    for( let i in commmentBoxes) {
        const element: any = commmentBoxes[i];
        const attributs = element.attributes;
        for(let j in attributs) {
            const attribute = attributs[j];
            if (attribute.nodeName === 'ng-reflect-name' && attribute.nodeValue === `update-${fieldName}`) {
                element.focus();
            }

        }

    }

}

添加cdkFocusInitial指令對我cdkFocusInitial

<input
    matInput
    cdkFocusInitial />

有時您可以在 html 中使用屬性autofocus ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM