Angular blur event tutorial with examples


In this tutorial, We will learn how to use input onBlur event in Angular

First, what is onBlur event? where this being used in Angular?

onBlur is an javascript event , fired when input element lost its focus. This will be applied to following input form elements

  • text
  • textarea
  • checkbox
  • readio
  • button
  • label

Other versions available:

This will be very helpful while doing form validations.

html onblur Syntax

<inputelement onBlur="eventname"> </inputelement>

In Angular, This will be used to do form validation i.e client or server side. Like in html, Angular will be have blur event instead of onBlur.

We are going to explain Different examples using blur event in Angular

How to use onBlur event in Angular

onBlur event can be captured using event binding i In Angular, Event binding is used to bind the event to DOM element. Syntax is (event binding). This is one way binding to bind the data from html to controller. Input element is added with blur attribute which called once the focus lost from this input. $event is passed to the blur method.

<div>
    <h2>{{ heading | titlecase }}</h2>
    <input type="text" (blur)="blurEvent($event)">
    <div>
        Output is {{enteredEmail}}
    </div>
</div>

Declared method which being called upon focus lost from html. Input value is read using event.target.value.

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  heading="angular blur tutorial with examples";
  enteredEmail:string="";
  
  blurEvent(event: any) {
    this.enteredEmail=event.target.value;
    console.log(this.enteredEmail);
}
}

two way binding with blur

In Angular, Two way binding is achieved with ngModel attribute. ngModel attributes binding from controller to html and html to controller

In order to two way binding work, please include formsmodule in application module.

    <input type="text" [(ngModel)]="email" (blur)="blurEvent()">

declare binding variable in controller, In the blur event, You can directly access the variable

  enteredEmail: string = '';
  email: string = '';
  blurEvent(event: any) {
    this.enteredEmail = this.email;
    console.log(this);
  }

Service call while onBlur event

blur template driven input form validation

First, Template driven form are one of angular form handling, allow you to do form validation These uses ngModel and ngModelOptions, local reference with hash.

This works since angular 5 version Template input form component has no form method defined.

  • input element has ngModel directive to have two way binding
  • ngModelOptions directive added to change the behaviour of ngModel
  • here email model bonded to blur event of updateOn
  • emailerror reference created to catch errors,true - email is empty, false - email already entered
  • This will enable email required validation displayed to the user
<div>
    <h2>{{ heading | titlecase }}</h2>
    <input type="text" [(ngModel)]="email" [ngModelOptions]="{ updateOn: 'blur' }" #emailerror="ngModel" required />
    <div *ngIf="!emailerror.valid">
        <span style="background-color: red">Email is required </span>
    </div>
    <button type="submit ">Submit</button>
</div>

template form component controller has to declare ngModel attribute value email.

import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  heading = 'angular blur validation with examples';

  email: string = '';
  constructor() {}
}

reactive input form validation with updateOn-blur event

Reactive forms is another form approach handling input data, It uses FormGroup and formControlName.

  • form component declared emailForm of type FormGroup
  • emailForm instance is created with FormGroup, contains validators and updateOnof blur event .
  • emailForm is bounded to template form defined.
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  heading = 'angular blur validation with examples';
  emailForm: FormGroup;

  myusername: string = '';
  constructor() {
    this.emailForm = new FormGroup({
      email: new FormControl('', {
        validators: Validators.required,
        updateOn: 'blur',
      }),
    });
  }
}

App component html for displaying input form as well as validation error

  • Declared form with formGroup directive to bind the emailForm to FormGroup
  • Added formControlName to input element
  • There is blur event configured in app component html
  • display errors if form control is not valid and touch event passed
<div>
    <h2>{{ heading | titlecase }}</h2>
    <form [formGroup]="emailForm">
        <input type="text" formControlName="email" />
        <div *ngIf="
        !emailForm.controls['email'].valid &&
        emailForm.controls['email'].touched
      ">
            <span style="background-color: red">Email is required </span>
        </div>
    </form>
    <button type="submit ">Submit</button>
</div>

And output displayed in the browser is

Angular reactive form validation updateOn blur example

Conclusion

In this tutorial, you learned following things

  • blur event usage in angular
  • blur event with ngModel
  • blur validation in template form inputs, ngModelOptions
  • reactive form validation using blur
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.