2017-10-13 58 views
4

我是Angular的新手,並且試圖用它來設置ID爲「input1」的輸入焦點。我使用下面的代碼:如何使用Angular4通過元素ID設置焦點

@ViewChild('input1') inputEl: ElementRef; 

然後在組件後:

this.inputEl.nativeElement.focus(); 

但它無法正常工作。我究竟做錯了什麼?任何幫助都感激不盡。

+0

https://stackoverflow.com/questions/38307060/how-to-set-focus-on-element-with-binding –

+0

輸入是動態生成的PrimeNg模板的一部分。我使用jquery在元素上設置id,但我不知道如何設置[focus]。有另一種方法嗎? –

+0

謝謝@Z.Bagley!你提到的問題中的答案之一就是解決方案。 –

回答

1

一個由@ Z.Bagley中提到的問題的答案給了我答案。我必須從@ angular/core將Renderer2導入到我的組件中。然後:

const element = this.renderer.selectRootElement('#input1'); 

setTimeout(() => element.focus(), 0); 

謝謝@MrBlaise的解決方案!

7

組件

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

@ViewChild('input1') inputEl:ElementRef; 

ngAfterViewInit() { 
     this.inputEl.nativeElement.focus(); 
} 

HTML

<input type="text" #input1> 
+0

如果組件的id是動態生成的,該怎麼辦? –

+0

你的意思是輸入的id?我認爲這不是可能的。 –

相關問題