How to user updateOn blur in FormBuilder
Asked Answered
V

2

16

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')
});
Vivianne answered 26/2, 2020 at 22:56 Comment(2)
you need use in the way "options" {validators:...,asyncValidators:...,updateOn:'blur'}, see #52167648Dominion
I think @Dominion has the right idea. Check out the docs: angular.io/api/forms/…Grantor
D
18

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: []}]})
Disillusionize answered 11/11, 2020 at 19:36 Comment(2)
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?Farcical
The second option doesn't seem to work anymore since Angular 14.Gott
H
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'}]
   // ...
});
Hussein answered 5/4, 2021 at 7:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.