Codementor Events

Auto-Focus with Angular 7: The Directive

Published Oct 29, 2018Last updated Nov 01, 2018
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 application.

https://vimeo.com/297743310

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:

See more at https://matthewdavis.io!

Discover and read more posts from Matthew Davis
get started
post commentsBe the first to share your opinion
Marcin Żmigrodzki
4 years ago

Many thanks! You saved my day, although there are two tiny mistakes:

  1. import {AutofocusDirective} from ‘./auto-focus.directive’; not import {AutoFocusDirective} from ‘./auto-focus.directive’;
  2. autoFocus not appAutoFocus
    But again, thank you very much!
Chumillas MC
5 years ago

Clear and concise Matt, good job.

Aleksandr Pankov
5 years ago

hi,
Do we really need timeOut hook when AfterContentInit is used?

Show more replies