Monday, 5 March 2018

Angular auto focus for input box - Angular

AngularAuto FocusAuto focus directive

In this article we will be discussing about setting an autofocus for a text box and also setting focus on a click. Let us check with some examples.

1. Auto focus on textbox using directive.
2. Set focus on text box on click.
3. Auto focus on textbox without using a directive.

1. Auto focus on textbox using directive


Especially while dealing with forms you may need to set default focus on some fields. We are going to create a simple angular directive to achieve this. Once directive is ready we can assign a Boolean value directly to the html. Let us check directive code first.

Directive


import { OnInit, ElementRef, Renderer, Input, Directive } from '@angular/core';

@Directive({ selector: '[focuMe]' })
export class FocusDirective implements OnInit {

    @Input('focuMe') isFocused: boolean;

    constructor(private hostElement: ElementRef, private renderer: Renderer) { }

    ngOnInit() {
        if (this.isFocused) {
            this.renderer.invokeElementMethod(this.hostElement.nativeElement, 'focus');
        }
    }
}

Angular 8(+)

If you are using Angular 8(+) in your application, then please consider below changes. Because Renderer is deprecated and now we have to use Renderer 2. invokeElementMethod is not available in Renderer 2. Update the directive code like below.


if (this.isFocused) {
   this.hostElement.nativeElement.focus();
}

Our directive is ready. focuMe is the name of the directive selector. Don't forget to import the dependencies OnInit, ElementRef, Renderer, Input and Directive. Also update the module by adding directive name (FocusDirective) under module declarations. Now check the html for the same.


<input type="text" [(ngModel)]="term1" [focuMe]="true">

You can assign true or false, also you can set the flag in your component as well.

html


<input type="text" [(ngModel)]="term2" [focuMe]="isFocus">

component


import { Component } from '@angular/core';

@Component({
  selector: 'app-general',
  templateUrl: './general.component.html',
  styleUrls: ['./general.component.scss']
})
export class GeneralComponent {

  isFocus: boolean = true;
}

Complete directive code for Angular 8(+) application

import {OnInit, ElementRef, Input, Directive} from '@angular/core';

@Directive({selector: '[focuMe]'})
export class FocusDirective implements OnInit {

  @Input('focuMe') isFocused: boolean;

  constructor(private hostElement: ElementRef) {
  }

  ngOnInit() {
    if (this.isFocused) {
      this.hostElement.nativeElement.focus();
    }
  }
}


We are done, our auto focus angular directive is ready to use.

2. Set focus on text box on click.


In the above example we have created a simple directive to set auto focus on text box. Now check another scenario of adding a focus on click. Check the below html code first.


<button (click)="setFocus()">Set Focus</button>
<input type="text" [(ngModel)]="term2" #inputBox>

Please not we have added #inputBox along with the text box. Same will be using to set the focus. Check the component code now.


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

@Component({
  selector: 'app-general',
  templateUrl: './general.component.html',
  styleUrls: ['./general.component.scss']
})
export class GeneralComponent {

  @ViewChild("inputBox") _el: ElementRef;

  setFocus() {
    this._el.nativeElement.focus();
  }
}

On click of setFocus method focus will set to the text box. Same code you can use for setting the autofocus as well. Let us check that code as well.

3. Auto focus on textbox without using a directive.



<input type="text" [(ngModel)]="term2" #inputBox>


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

@Component({
  selector: 'app-general',
  templateUrl: './general.component.html',
  styleUrls: ['./general.component.scss']
})
export class GeneralComponent {

  @ViewChild("inputBox") _el: ElementRef;

  setFocus() {
    this._el.nativeElement.focus();
  }
  ngAfterViewInit() {
    this._el.nativeElement.focus();
  }
}

Here we are setting the autofocus on ngAfterViewInit angular life cycle.

We are done. In this article I have explained about setting an auto focus with and without using a directive and also setting focus on click.

AngularAuto FocusAuto focus directive

Related Info

1. 3 simple ways to share data through angular route.

2. Get Url parameter using Angular.

3. Truncate file name without hiding the extension using Angular Pipe.

4. Conditionally add class using Angular - 5 methods

6 comments :

  1. Hello, I wish for to subscribe for this blog to get most recent
    updates, thus where can i do it please assist.

    ReplyDelete
  2. Thank you! It is helped for me.

    ReplyDelete
  3. this does not work with Angular 8

    ReplyDelete
    Replies
    1. Thanks,I have updated the blog accordingly.

      Delete
  4. I used your directive in my app. Very elegant and reusable solution. Thank you!

    ReplyDelete