Search code examples
angularfocusdirective

create a directive to enable focus on input fields


I try to activate the focus in many of the inputs in my application. Instead of duplicating code, I thought I would create a custom directive but I can’t. If someone can help me.. Here's my bad code : directive:

import { AfterViewInit, Directive, ElementRef, ViewChild } from '@angular/core';

@Directive({
  selector: '[appFocus]'
})
export class FocusDirective implements AfterViewInit {
  @ViewChild('zone') zoneInput: ElementRef;
  constructor() { }

  ngAfterViewInit() {
     this.zoneInput.nativeElement.focus();
  }

}

in a template:

        <div>
            <mat-form-field class="example-full-width" appearance="fill">
                <mat-label>Saisie code barre</mat-label>
                <input appFocus matInput formControlName="barcode" placeholder="EAN...">
            </mat-form-field>
        </div>

Thank you very much


Solution

  • You're close!

      constructor(private el: ElementRef) {}
    
      ngAfterViewInit(): void {
        this.el.nativeElement.focus();
      }
    

    You need to actually pass the element in so that you have access to the native Element to focus on, not the zoneInput. You may or may not need to wrap in a setTimeout, but this should get you what you need.