Angular2+ autofocus input element

angular 7 autofocus
angular 6 autofocus directive
angular autofocus directive
angular 8 autofocus
autofocus input angular 8
angular 4 focus input element
html autofocus
auto focus form field

How can I autofocus input element? Similar to this question, but not with AngularDart. Something like this:

<input type="text" [(ngModel)]="title" [focus] />
//or 
<input type="text" [(ngModel)]="title" autofocus />

Does Angular2 has any build in support for this feature?

Best close question is this one, but is there any shorter/easier solution, since I do not have "list of input boxes". In provided link *ngFor="#input of inputs" is used, but I only have 1 input in control template.

This is my current code:

import { Directive, ElementRef, Input } from "@angular/core";

@Directive({
    selector: "[autofocus]"
})
export class AutofocusDirective
{
    private focus = true;

    constructor(private el: ElementRef)
    {
    }

    ngOnInit()
    {
        if (this.focus)
        {
            //Otherwise Angular throws error: Expression has changed after it was checked.
            window.setTimeout(() =>
            {
                this.el.nativeElement.focus(); //For SSR (server side rendering) this is not safe. Use: https://github.com/angular/angular/issues/15008#issuecomment-285141070)
            });
        }
    }

    @Input() set autofocus(condition: boolean)
    {
        this.focus = condition !== false;
    }
}

use case:

[autofocus] //will focus
[autofocus]="true" //will focus
[autofocus]="false" //will not focus

Outdated code (old answer, just in case): I ended up with this code:

import {Directive, ElementRef, Renderer} from '@angular/core';

@Directive({
    selector: '[autofocus]'
})
export class Autofocus
{
    constructor(private el: ElementRef, private renderer: Renderer)
    {        
    }

    ngOnInit()
    {        
    }

    ngAfterViewInit()
    {
        this.renderer.invokeElementMethod(this.el.nativeElement, 'focus', []);
    }
}

If I put code in ngOnViewInit it does not work. Code also use best practices, since calling focus on element directly is not recommended.

Edited (conditional autofocus): A few days ago I needed conditional auto focus, because I hide first autofocus element and I want to focus another, but only when first is not visible, and I ended with this code:

import { Directive, ElementRef, Renderer, Input } from '@angular/core';

@Directive({
    selector: '[autofocus]'
})
export class AutofocusDirective
{
    private _autofocus;
    constructor(private el: ElementRef, private renderer: Renderer)
    {
    }

    ngOnInit()
    {
    }

    ngAfterViewInit()
    {
        if (this._autofocus || typeof this._autofocus === "undefined")
            this.renderer.invokeElementMethod(this.el.nativeElement, 'focus', []);
    }

    @Input() set autofocus(condition: boolean)
    {
        this._autofocus = condition != false;
    }
}

Edited2: Renderer.invokeElementMethod is deprecated and new Renderer2 does not support it. So we are back to native focus (which doesn't work outside DOM - SSR for example!).

import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
    selector: '[autofocus]'
})
export class AutofocusDirective
{
    private _autofocus;
    constructor(private el: ElementRef)
    {
    }

    ngOnInit()
    {
        if (this._autofocus || typeof this._autofocus === "undefined")
            this.el.nativeElement.focus();      //For SSR (server side rendering) this is not safe. Use: https://github.com/angular/angular/issues/15008#issuecomment-285141070)
    }

    @Input() set autofocus(condition: boolean)
    {
        this._autofocus = condition != false;
    }
}

use case:

[autofocus] //will focus
[autofocus]="true" //will focus
[autofocus]="false" //will not focus

How to set autofocus in angular or angular 2 not angularjs, In your html add #nameit to get its reference in component code. <input type="text​" name="me" #nameit>. Then apply auto fouces into it. autofocus is an HTML5 attribute that doesn’t work consistently across different browsers when a (form) element is inserted dynamically into the DOM after the initial page load.

autofocus is a native html feature that should work at least for page initialization. However it fails to work with many angular scenarios, especially with *ngIf.

You can make a really simple custom directive to get desired behaviour.

import { Directive, OnInit, ElementRef } from '@angular/core';

@Directive({
  selector: '[myAutofocus]'
})
export class AutofocusDirective implements OnInit {

  constructor(private elementRef: ElementRef) { };

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

}

The above directive works for my use cases.

How to use

<input *ngIf="someCondition" myAutofocus />

EDIT: There seems to be usecases where it is to early to call focus in the OnInit lifecycle method. If that is the case, change to OnAfterViewInit instead.

Adding autofocus to an input field in an Angular 5 Bootstrap 4 , A couple of days back I faced trouble adding autofocus to an input field that was rendered inside a Bootstrap modal. The project is built using  Let’s start by adding an input element and a button to our component’s template. Now we can access the input element in our component’s code and call the .focus () method on its native element, like the following code snippet shows. Therefore, we need to make sure to have imported ViewChild and ElementRef.

The following directive works for me using Angular 4.0.1

import {Directive, ElementRef, AfterViewInit} from '@angular/core';

@Directive({
  selector: '[myAutofocus]'
})
export class MyAutofocusDirective implements AfterViewInit {
  constructor(private el: ElementRef)
  {
  }
  ngAfterViewInit()
  {
    this.el.nativeElement.focus();
  }
}

use it like this:

<md-input-container>
    <input mdInput placeholder="Item Id" formControlName="itemId" name="itemId" myAutofocus>
</md-input-container>

The option of using OnInit lifecycle event did not work for me. I also tried using the Renderer in the other answer which didn't work for me.

Creating An Input-Driven AutoFocus Directive In Angular 5.0.2, HTML form elements already provide for an "autofocus" attribute that will pull focus to an input field after it is rendered on the page. This is great  Add a local template variable to your input element: <input #input1>, and get a reference to it using @ViewChild('input1') input1ElementRef;. Then, wherever you are setting modalOpen to true, also set focus on the input element with this._renderer.invokeElementMethod(this.input1ElementRef.nativeElement, 'focus', []). Using Renderer is web worker safe.

You could assign the input element a template reference variable #myInput:

<input type="text" [(ngModel)]="title" #myInput />

Let your component implement AfterViewInit, grab the reference of the input element with the ViewChild annotation and focus your element in the ngAfterViewInit hook:

export class MyComponent implements AfterViewInit {
    @ViewChild("myInput") private _inputElement: ElementRef;

    [...]

    ngAfterViewInit(): void {
        this._inputElement.nativeElement.focus();
    }
}

Auto-Focus with Angular 7: The Directive, Making input elements have “auto-focus” capability can be a cumbersome process. In this exercise we will use an Angular Directive which will allow our  This answer is inspired by post Angular 2: Focus on newly added input element. Steps to set the focus on Html element in Angular2. Import ViewChildren in your Component. import { Input, Output, AfterContentInit, ContentChild,AfterViewInit, ViewChild, ViewChildren } from 'angular2/core';

<input type="text" [(ngModel)]="title" #myInput />
{{ myInput.focus() }}

just add {{ myInput.focus() }} right after input inside template

Make It Easy: Angular auto focus for input box, AngularAuto FocusAuto focus directive. In this article we will be discussing about setting an autofocus for a text box and also setting focus on a  Angular 2/4 set focus on input element. Ask Question Asked 2 years, giving a name to your input element and wiring up a click event in your template.

Focusing on Form Elements The Angular Way, Form field focus is something we have to deal with a lot when it comes to building forms. When a user clicks an “update” button we want to  What I did is using regular autofocus on my inputs: <input autofocus> And then I set the focus on the first visible input with autofocus when angular is ready: angular.element(document).ready(function() { $('input[autofocus]:visible:first').focus(); }); Hope this helps.

Angular 2 // Element autofocus · GitHub, <input #myInput type="text" />. <div> Some other content </div>. ` }) export class MyComp implements AfterViewInit {. @ViewChild('myInput') input: ElementRef;. None of the combinations worked. Currently I have autofocus on the input. If the site is loaded on the sign-in page (for example), it works as intended. If the home page is loaded and I navigate to the sign-in page, it looks like it focuses then immediately blurs, triggering the validation on the field.

korniychuk/angular-autofocus-fix: Angular 5+ directive for , Angular 5+ directive for fix autofocus on dynamically created controls (*ngIf, *​ngFor, etc.). Uses native [autofocus] selector, no need to change your HTML template. directive/component that has some binding related to focus of the element. Conditionally add class to an element on click - angular Disable submit button until all mandatory fields are filled - Angular Select all/ deselect all checkbox - Angular File upload validation - Angular Angular auto focus for input box - Angular Multiselect checkbox dropdown component using Angular

Comments
  • second alternative should work straight out of the box. It doesn't?
  • Simply using "autofocus" doesn't work because that is only effective when the page loads, not when Angular is swapping content in and out.
  • What about binding: [attr.autofocus]="condition"?
  • This is what I ended with too, after reading through this ... angularjs.blogspot.co.uk/2016/04/…
  • I used this code, and the OnInit worked for me. I didn't have to use the AfterViewInit.
  • @Rodrigo: I wanted to be sure.
  • Great answer! Thanks Makla
  • Great answer! Worked for me.
  • I would rather see basic approach (attribute in template), so I don't need to write all this code in every page that has form.
  • Cannot read property 'nativeElement' of undefined - Getting error on console
  • @HasmukhBaldaniya Did you add the template reference variable? And are you sure, you're accessing _inputElement after the view has been initialized?
  • I was getting "Cannot read property 'focus' of undefined." It was due to my template reference variable being linked to data (#myInput="ngModel" in the template). The solution was to make a second template reference variable for that field.