I have using reactive form and form have 60 fields. so I have written asyncvalidtors for server-side validation.
Note: Not using value changes mechanism.it works with below two line
formGroup.ProductId.setErrors(null, { onlySelf: true, emitEvent: false });
formGroup.ProductId.updateValueAndValidity({ onlySelf: true, emitEvent:false});
Problem with Validators Mechanism
I have faced an issue in the following scenarios. In async validators, I have use case if productName control is valid and set error null for productId fields.i have set the errors, and while perform updateValueandValidity send another request to the server .
if(result.controlName =='ProductName' && result.Validation==true){
// if control Name is productName // set Errors as Null for Product ID
formGroup.ProductId.setErrors(null, { onlySelf: true, emitEvent: false });
formGroup.ProductId.updateValueAndValidity({ onlySelf: true, emitEvent: false });
//But it recursively call while perform this line
}
validators
export class SomeAsyncValidator {
static createValidator = (someService: SomeService) => (control: AbstractControl) =>
timer(500)
.pipe(
debounceTime(2000)
// If previous query is different from current
, distinctUntilChanged(),
map(() => control.value),
switchMap((name) => someService.exists({ request })),
map(() => ({
if(result.controlName =='ProductName' && result.Validation==true){
// if control Name is productName // set Errors as Null for Product ID
formGroup.ProductId.setErrors(null, { onlySelf: true, emitEvent: false });
formGroup.ProductId.updateValueAndValidity({ onlySelf: true, emitEvent: false });
//But it recursively call while perform this line
}
})),
catchError(() => of(null)));
}
updateValueAndValidity({ onlySelf: true }){ onlySelf: true, emitEvent: false }forget to add in question updateddistinctUntilChanged()in the pipesetErrorsmanually while trying to use valdiators. you shouldn't be doing that, so this seems like a design problem. if your validation involves multiple fields, it should probably be a group validator. you should describe the actual problem you're trying to solve here so you can get help with your design.