I have to find if one of my formcontrols has a pattern error. If it has a pattern error, then I have to change the value of that formcontrol to null.
I wrote a recursive method that calls itself to check if one f the form control has a pattern error and then it finally returns true or false, But what I want is to change the value of that formcontrol to null
Here is my recursive function,
hasPatternError(form: AbstractControl, isRecursion = false): boolean {
if (!isRecursion) {
this.patternErrors = [];
}
if (form instanceof FormControl) {
return form.hasError('pattern') === true ?? null;
}
if (form instanceof FormArray) {
form?.controls?.forEach(e => {
this.hasAnyPatternError(e, true);
});
}
if (form instanceof FormGroup) {
Object.keys(form.controls).forEach(key => {
const error = this.hasAnyPatternError(form.get(key), true);
if (error === true) {
this.patternErrors.push(error);
}
});
return this.patternErrors.length > 0 ? true : false;
}
}
This is my form, listening to value changes event. On the change event, I am calling the above recursive method to find if any of the form control has a pattern error but stuck on changing the value of that formcontrol to null.
Note: I want the method (hasPatternError) to return an object(that has error converted to null and not expecting the form to change realtime)
ngOnInit() {
this.myForm = this.fb.group({
name: [''],
address: this.fb.group({
street: [''],
zip: [''],
licenseNo: ['', [Validators.required, Validators.pattern(/^[a-z0-9]{10}$/i)]],
})
})
this.myForm.valueChanges.subscribe(
data => {
console.log(this.hasAnyPatternError(this.myForm))
}
);
}
Here is my code on stackblitz