How to use onBlur event on Angular2?

Ignat picture Ignat · Jan 21, 2016 · Viewed 221.7k times · Source

How do you detect an onBlur event in Angular2? I want to use it with

<input type="text">

Can anyone help me understand how to use it?

Answer

Pankaj Parkar picture Pankaj Parkar · Jan 21, 2016

Use (eventName) for while binding event to DOM, basically () is used for event binding. Also use ngModel to get two way binding for myModel variable.

Markup

<input type="text" [(ngModel)]="myModel" (blur)="onBlurMethod()">

Code

export class AppComponent { 
  myModel: any;
  constructor(){
    this.myModel = '123';
  }
  onBlurMethod(){
   alert(this.myModel) 
  }
}

Demo

Alternative(not preferable)

<input type="text" #input (blur)="onBlurMethod($event.target.value)">

Demo


For model driven form to fire validation on blur, you could pass updateOn parameter.

ctrl = new FormControl('', {
   updateOn: 'blur', //default will be change
   validators: [Validators.required]
}); 

Design Docs