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.
hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With