15

I have a custom async validator, and I want to set updateOn: 'blur' property using FormBuilder:

myForm = this.formBuilder.group({
   email: ['', [Validators.required], [this.myAsyncValidator]]
   // ...
});

I tried this but it does not work:

email: ['', [Validators.required], [this.myAsyncValidator, {updateOn: 'blur'}]]

Note

I DO NOT want to create form control instances manually like the following:

myForm = new FormGroup({
    email: new FormControl('', {asyncValidators: [this.myAsyncValidator]}, updateOn: 'blur')
});
A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
  • you need use in the way "options" {validators:...,asyncValidators:...,updateOn:'blur'}, see https://stackoverflow.com/questions/52167148/use-updateon-blur-in-angular-reactive-forms/52167538 – Eliseo Feb 26 '20 at 23:18
  • I think @Eliseo has the right idea. Check out the docs: https://angular.io/api/forms/AbstractControlOptions#abstractcontroloptions – Keenan Diggs Feb 27 '20 at 04:17

2 Answers2

16

there are two ways to achieve that -

myForm = this.formBuilder.group({email: this.formBuilder.control('', {updateOn: 'blur', validators: [], asyncValidators: []})})

or,

myForm = this.formBuilder.group({email: ['', {updateOn: 'blur', validators:[], asyncValidators: []}]})
Nawaz Sharif
  • 171
  • 1
  • 7
  • 1
    Welcome, Nawaz. Instead of just including code, could you _edit_ your answer to _also_ provide an explanation? Why do these work, whereas the OP's code doesn't? What's doing the work here? Is there a reason one of these syntaxes might be preferred over the other? – Jeremy Caney Nov 11 '20 at 22:25
  • 2
    The second option doesn't seem to work anymore since Angular 14. – Felix Sep 12 '22 at 07:02
9

I want to add more answer for this question.

Here is the code at the library:

enter image description here

So, from your question, look like you are trying to set updateOn for email formControl and you are setting 3 arguments. This is not correctly.

Change

myForm = this.formBuilder.group({
   email: ['', [Validators.required], [this.myAsyncValidator]]
   // ...
});

to

myForm = this.formBuilder.group({
   email: ['', {validators: Validators.required, asyncValidators: this.myAsyncValidator, updateOn: 'blur'}]
   // ...
});
Hoang Subin
  • 6,610
  • 6
  • 37
  • 56