Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fire Angular 5 async validator onblur for FormGroup

I am using Angular version 5.0.1 and I'm trying to fire an AsyncValidator on a FormGroup on a blur event on one of the FormControls in the FormGroup.

I can get onBlur to work on a form control using the following:

name: ['', {updateOn: 'blur'}]

However, when I try to apply it to a FormGroup it doesn't work.

Is it possible to only fire an AsyncValidator onBlur on a FormGroup, and if not, what is the best way to execute the validator only when the user has finished entering data?

My only other option at the moment is to us some sort of debounce wrapper for my validator.

Just reading through here and it appears I should be able to use updateOn: 'blur' for a form group.

After new FormGroup(value, {updateOn: 'blur'})); new FormControl(value, {updateOn: 'blur', asyncValidators: [myValidator]})

like image 392
BSimpson Avatar asked Nov 09 '17 03:11

BSimpson


2 Answers

In Angular5 Specifying the update mode is possible for both types of forms: template-driven forms and reactive forms.

First one is working for you. Here's the working example for reactive forms

Component.ts

 import { Component, OnInit } from '@angular/core';
    import { FormGroup, FormControl, Validators } from '@angular/forms';
    @Component({
      selector: 'form01',
      templateUrl: './student.component.html',
      styleUrls: ['./student.component.scss']
    })
    export class StudentComponent implements OnInit {
    formTitle:string="Student registration ";
    nameForm: FormGroup;

    constructor() {
    }

    ngOnInit() {
      this.nameForm = new FormGroup ({
        firstname: new FormControl('', {
          validators: Validators.required,
          asyncValidators: [yourAsyncValidatorFunction],
          updateOn: 'blur'
        }),
        lastname: new FormControl('', {
          validators: Validators.required,
          asyncValidators: [yourAsyncValidatorFunction],
          updateOn: 'blur'
        })
      });
    }
    }

HTML

<form [formGroup]="nameForm" novalidate>
  <div class="form-group">
    <label>What's your first name? </label>
    <input class="form-control" formControlName="firstname">
  </div>
  <div class="form-group">
    <label>What's your last name?</label>
    <input class="form-control" formControlName="lastname">
  </div>
  <button type="submit" class="btn btn-success">Submit</button>
</form>

  <h3>Hello {{nameForm.value.firstname}} {{nameForm.value.lastname}}</h3>
like image 51
Vishnu T S Avatar answered Sep 22 '22 03:09

Vishnu T S


It works on my side. Be aware that the FormBuilder may not support this yet.

this.formGroup = new FormGroup({
  name: new FormControl('', {validators: []})
}, {
  updateOn: 'blur'
});
like image 23
Niels Steenbeek Avatar answered Sep 19 '22 03:09

Niels Steenbeek