Ignat
Ignat

Reputation: 3787

How to use onBlur event on Angular2?

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?

Upvotes: 147

Views: 338628

Answers (9)

taggartJ
taggartJ

Reputation: 287

I ended up doing something like this in Angular 14

<form name="someForm" #f="ngForm" (ngSubmit)="onSubmit(f)"> ...
<input
 matInput
 type="email"
 name="email"
 autocomplete="email"
 placeholder="EMAIL"
 [ngModel]="payload.email"
  #email="ngModel"
  (blur)="checkEmailBlur(f)"
  required
  email
  tabindex="1"
  autofocus
 />

then ... in .ts

 checkEmailBlur(f: NgForm) {
     const email = f.value.email;

Upvotes: 0

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

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

Upvotes: 269

Kevy Granero
Kevy Granero

Reputation: 783

Another possible alternative

HTML Component file:

<input formControlName="myInputFieldName" (blur)="onBlurEvent($event)">

TypeScript Component file:

import { OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

export class MyEditComponent implements OnInit {

    public myForm: FormGroup;
    
    constructor(private readonly formBuilder: FormBuilder) { }
    
    ngOnInit() {

        this.myForm = this.formBuilder.group({
            
            myInputFieldName: ['initial value', { validators: [Validators.required, Validators.maxLength(100), anotherValidator], updateOn: 'blur' }],

        });
    }

    onBlurEvent(event) {
        
        // implement here what you want

        if (event.currentTarget && event.currentTarget.value && event.currentTarget.value !== '') { }

    }
}

Upvotes: 2

Aniket kale
Aniket kale

Reputation: 677

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
 }
}

Upvotes: 19

Apurv Chaudhary
Apurv Chaudhary

Reputation: 1795

you can use directly (blur) event in input tag.

<div>
   <input [value]="" (blur)="result = $event.target.value" placeholder="Type Something">
   {{result}}
</div>

and you will get output in "result"

Upvotes: 8

Kevin Black
Kevin Black

Reputation: 916

Try to use (focusout) instead of (blur)

Upvotes: 2

Sathish Visar
Sathish Visar

Reputation: 105

HTML

<input name="email" placeholder="Email"  (blur)="$event.target.value=removeSpaces($event.target.value)" value="">

TS

removeSpaces(string) {
 let splitStr = string.split(' ').join('');
  return splitStr;
}

Upvotes: 3

user394749
user394749

Reputation:

This is the proposed answer on the Github repo:

// example without validators
const c = new FormControl('', { updateOn: 'blur' });

// example with validators
const c= new FormControl('', {
   validators: Validators.required,
   updateOn: 'blur'
});

Github : feat(forms): add updateOn blur option to FormControls

Upvotes: 1

Er Mariam Akhtar
Er Mariam Akhtar

Reputation: 21

/*for reich text editor */
  public options: Object = {
    charCounterCount: true,
    height: 300,
    inlineMode: false,
    toolbarFixed: false,
    fontFamilySelection: true,
    fontSizeSelection: true,
    paragraphFormatSelection: true,

    events: {
      'froalaEditor.blur': (e, editor) => { this.handleContentChange(editor.html.get()); }}

Upvotes: 1

Related Questions