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 functionality to be re-used throughout your application.

First, let’s create the Directive

auto-focus.directive.ts

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

@Directive({
    selector: '[autoFocus]'
})
export class AutofocusDirective implements AfterContentInit {

    @Input() public appAutoFocus: boolean;

    public constructor(private el: ElementRef) {

    }

    public ngAfterContentInit() {

        setTimeout(() => {

            this.el.nativeElement.focus();

        }, 500);

    }

}

Next we need to tell our AppModule that this new directive exists and to declare it for availability by updating our app.module.ts:

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

import {AppComponent} from './app.component';
import {AutoFocusDirective} from './auto-focus.directive';

@NgModule({

    declarations: [
        AppComponent,
        AutoFocusDirective
    ],
    imports: [
        BrowserModule
    ],
    providers: [],
    bootstrap: [AppComponent]

})
export class AppModule {
}

Now let’s use it in a component

app.component.html

<div>
    
    Autofocus? <input appAutoFocus>

</div>

See also: