Reactive Forms

Creating an Angular Directive - Auto Focus Form Control

Published on

I was working on a side project with a lot of forms and want a simple way to set focus to a specific form control on each page/view when the page/view loads. The code snippet below is my current solution for this. import { AfterViewInit, Directive, ElementRef } from '@angular/core'; @Directive({ selector: 'input[fooAutoFocusControl],textarea[fooAutoFocusControl],select[fooAutoFocusControl]' }) export class FooAutoFocusControlDirective implements AfterViewInit { constructor( private _elementRef: ElementRef ) { } ngAfterViewInit(): void { this.