簡體   English   中英

是否有一種 Angular2 方法可以專注於輸入字段?

[英]Is there an Angular2 way to focus on an input field?

在方法結束時,我將清除一些字段,這很容易:

this.modelname.fieldname1 = "";
this.modelname.fieldname2 = "";

清除字段后,我希望光標出現在field1

有沒有 Angular2 的方法來做到這一點,還是我只使用老式的 Javascript?

不建議在 Angular 中直接訪問 dom。 Angular 提供了 Renderer (Angular2) 和 Renderer 2(Angular4) 抽象。

以下是在 Angular 2 中的操作方法:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input #inp id="myInput" type="text">
      <button (click)="setFocus()">Set Focus</button>
    </div>
  `,
})
export class App {
  @ViewChild('inp') inp:ElementRef;

  constructor(private renderer: Renderer) {
  }

  setFocus() {
    this.renderer.invokeElementMethod(this.inp.nativeElement, 'focus');
  }
}

在 Angular4 中,Renderer 被棄用,Renderer2 被添加。 invokeElementMethod 被刪除了,有一個關於它的討論: https : //github.com/angular/angular/issues/13818#issuecomment-297815331

這是 Angular 4 的方式:

 let onElement = this.renderer2.selectRootElement('#myInput');
 onElement.focus();

您可以在第一個輸入中使用模板引用變量,這將使您能夠在其上運行.focus()

在您的模板中,您可以將 #fieldName1 添加到您的輸入標簽(即<input type="text" #fieldName1>

在您的控制器中執行以下操作:

@ViewChild('fieldName1')
fieldName1: any;

現在您可以在控制器中執行this.fieldName1.nativeElement.focus()或在模板中執行fieldName1.focus()

使用@ViewChild裝飾器添加renderer方式。 您可以跳過上面@julia 提到的 #id 屬性。

一旦視圖初始化 Html,它將聚焦輸入元素:

<textarea  #tasknote name="tasknote"> </textarea> 

JS:

export class MyComponent implements AfterViewInit {
      @ViewChild('tasknote') input: ElementRef;
         constructor(private renderer: Renderer2){           
          }

       ngAfterViewInit() {
       //using selectRootElement instead of deprecated invokeElementMethod
       this.renderer.selectRootElement(this.input["nativeElement"]).focus();
      }

    }

了解更多關於renderer其他功能,請關注官方文檔

簡單的方法

 <input type="text" id="updateField" >

js/ts

   let element=document.getElementById('updateField');
             element.focus();  

如果遇到未定義的錯誤,請在 setTimeOut 中使用

 setTimeout(()=>{
                 let element=document.getElementById('updateField');
                 element.focus();                 
             },100)

如何設置輸入字段的焦點中獲得靈感 我通過創建一個設置元素焦點的屬性指令來實現這一點。 這意味着我不需要直接在我的組件控制器中引用元素並且它支持綁定。

import { Directive, ElementRef, Input } from "@angular/core";

@Directive({
    selector: "[appFocusMe]"
})
export class FocusMeDirective {

    @Input("appFocusMe") set focusElement(focus: boolean) {
        if (focus) {
            this.el.nativeElement.focus();
        }
    }

    constructor(private el: ElementRef) { }
}

然后在視圖中:

<input [appFocusMe]="true" />

暫無
暫無

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

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