How to use onBlur event on Angular2?
Use (eventName)
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 1
<input type="text" [ngModel]="myModel" (ngModelChange)="myModel=$event">
Alternative 2 (not preferable)
<input type="text" #input (blur)="onBlurMethod($event.target.value)">
Demo
For a 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
You can also use (focusout) event:
Use (eventName)
for while binding event to DOM, basically ()
is used for event binding. Also you can use ngModel
to get two way binding for your model
. With the help of ngModel
you can manipulate model
variable value inside your component
.
Do this in HTML file
<input type="text" [(ngModel)]="model" (focusout)="someMethodWithFocusOutEvent($event)">
And in your (component) .ts file
export class AppComponent {
model: any;
constructor(){ }
/*
* This method will get called once we remove the focus from the above input box
*/
someMethodWithFocusOutEvent() {
console.log('Your method called');
// Do something here
}
}