Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set autofocus in angular or angular 2 not angularjs

I see many posts in how to set autofocus on an input filed in angularjs by creating a directive or HTML autofocus, Is there a quick and easy way to set focus in angular (angular 2, angular 4 etc)

like image 217
Aniruddha Das Avatar asked Mar 17 '17 15:03

Aniruddha Das


1 Answers

In your html add #nameit to get its reference in component code.

<input type="text" name="me" #nameit>

Then apply auto fouces into it.

  @ViewChild('nameit') private elementRef: ElementRef;

  public ngAfterViewInit(): void {
    this.elementRef.nativeElement.focus();
  }
like image 173
Aniruddha Das Avatar answered Nov 04 '22 07:11

Aniruddha Das