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';

  selector: 'input[fooAutoFocusControl],textarea[fooAutoFocusControl],select[fooAutoFocusControl]'
export class FooAutoFocusControlDirective implements AfterViewInit {
    private _elementRef: ElementRef
  ) { }

  ngAfterViewInit(): void {

  public setFocusToControl(): void {
    setTimeout(() => this._elementRef.nativeElement.focus());

The concept is straight forward. Inject the ElementRef of the element containing the directive, then we access the native element and call the focus() method.

An example of this being used can be seen below.


After the component initializes, the focus should be set to this control!

comments powered by Disqus