How to set autofocus in angular or angular 2 not angularjs

<input id="name" type="text" #myInput />
{{ myInput.focus() }}

Add {{ myInput.focus() }} into your template.


Aniruddha Das' answer works well in some cases. However, if this is applied to a template-based form with required validation, you may get the following error:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after >it was checked. Previous value: 'false'. Current value: 'true'.

One solution to this is wrapping the focus() call within ngInit() instead of ngAfterViewInit(). So, extending upon Aniduddha's answer:

In your html add the #namedReference to the component:

<input type="text"
    placeholder="Your full name"
    name="name"
    ngModel
    #fullName="ngModel"
    required
    #nameit>

Then use onNgInit() to apply auto focus into it:

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

ngOnInit() {
    this.elementRef.nativeElement.focus();
}

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();
  }