![](/img/trans.png)
[英]Angular2: undefined errors when trying to set focus to an input field using @ViewChild annotation
[英]Angular 4: Viewchild set focus
我試圖在不使用標簽autofocus = true的情況下控制按鈕的焦點,但是似乎無法正常工作,您是否認為有必要使用管道?
<button #btn_focus>
@ViewChild('btn_focus') firstNameElement: ElementRef;
ngAfterViewInit(){
this.firstNameElement.nativeElement.focus();
}
謝謝。
我也有同樣的問題嘗試了多種方法,但沒有奏效。 最后,我使用javascript代碼專注於具有屬性ID的給定HTML元素。
function focusInputelement(id) {
window.setTimeout(() => {
document.getElementById(id).focus();
}, 500);
}
您的代碼正在運行,您可以在此處查看其運行情況:
https://stackblitz.com/edit/angular-6mszhb?file=app%2Fapp.component.ts
我敢打賭,您的問題只是打開了開發人員控制台,該控制台在頁面加載后立即失去了焦點。 嘗試在關閉(開發人員)開發人員控制台的情況下打開該stackblitz,然后打開控制台(並使其聚焦,因此您的光標在那里閃爍)並刷新頁面(不起作用)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.