How to use Angular4 to set focus by element id How to use Angular4 to set focus by element id angular angular

How to use Angular4 to set focus by element id


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>


One of the answers in the question referred to by @Z.Bagley gave me the answer. I had to import Renderer2 from @angular/core into my component. Then:

const element = this.renderer.selectRootElement('#input1');// setTimeout(() => element.focus, 0);setTimeout(() => element.focus(), 0);

Thank you @MrBlaise for the solution!


I also face same issue after some search I found a good solution as @GreyBeardedGeek mentioned that setTimeout is the key of this solution.He is totally correct. In your method you just need to add setTimeout and your problem will be solved.

setTimeout(() => this.inputEl.nativeElement.focus(), 0);