Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Angular4 to set focus by element id

I am new to Angular, and am trying to use it to set focus on an input with the id "input1". I am using the following code:

@ViewChild('input1') inputEl: ElementRef; 

then later in the component:

 this.inputEl.nativeElement.focus(); 

But it isn't working. What am I doing wrong? Any help will be much appreciated.

like image 457
Pismotality Avatar asked Oct 13 '17 00:10

Pismotality


People also ask

How do you know if an element is focused in angular?

hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.


1 Answers

Component

import { Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core'; ...   @ViewChild('input1', {static: false}) inputEl: ElementRef;      ngAfterViewInit() {    setTimeout(() => this.inputEl.nativeElement.focus()); } 

HTML

<input type="text" #input1> 
like image 140
Dmitry Grinko Avatar answered Sep 23 '22 17:09

Dmitry Grinko