Reputation: 496
I have an angular form with custom aync validators I want to do some stuff if the form is invalid on load.
Here is the code
ngOnInit() {
this.signupForm = this.fb.group({
name: [
'Prasad P',
[Validators.required, Validators.maxLength(3)],
ValidateUserNotTaken.createValidator(this.signupService)
],
email: [
'',
[Validators.required, Validators.email],
ValidateEmailNotTaken.createValidator(this.signupService)
]
});
// watch for status Changes
this.signupForm.statusChanges.subscribe(status => {
alert('Form Status Is ' + status);
if(status === 'INVALID') {
// do_stuff();
}
});
}
The statusChange event never emits a value when loaded once I change anything in form then the event emits and everything works but I really want to know the form is invalid on loading.
I try to run updateValueAndValidity() but it always hangs to PENDING state.
The stackbliz Link : https://stackblitz.com/edit/angular-async-custom-validation-vlz43u?file=src%2Fapp%2Fapp.component.ts
Upvotes: 2
Views: 2381
Reputation: 796
I tested your code in stackblitz and I added updateValueAndValidity()
after form has been created and it is working fine as expected. Please see this stackblitz.
The other alternative is you can patch your form values to your form to trigger the validation on page load. In the code below, I added setTimeout(() => { this.signupForm.patchValue(this.signupForm.value);});
to trigger the validation on page load. You need to add this after you created the form.
ngOnInit() {
this.signupForm = this.fb.group({
name: [
'Prasad P',
[Validators.required, Validators.maxLength(3)],
ValidateUserNotTaken.createValidator(this.signupService)
],
email: [
'',
[Validators.required, Validators.email],
ValidateEmailNotTaken.createValidator(this.signupService)
]
});
//Added to trigger form validation
setTimeout(() => {
this.signupForm.patchValue(this.signupForm.value);
});
// watch for status Changes
this.signupForm.statusChanges.subscribe(status => {
alert('Form Status Is ' + status);
if (status === 'INVALID') {
// do_stuff();
console.log('TEST');
}
});
}
Upvotes: 0