public

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

Latest Post Svelte 5 tables proper. by Matthew Davis public

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:

Matthew Davis

Published 5 years ago