I'm very simply trying to validate a control if its value matches a value within a FormArray.
I want to be clear that I do not want to validate the form or a FormGroup or a FormArray. This question is for learning how to pass parameters to a validator function and the validation of the addValue
control.
Here is what I have in my custom validation service:
public form: FormGroup = this.fb.group({
addValue: this.fb.control(null, [this.validatorService.duplicate(this.form.get('values'))]),
values: this.fb.array([])
});
And the validator function
public duplicate(values: FormArray): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
for (let i = 0, j = values.length; i < j; i++ ) {
if (control.value === values[i].value) {
return { 'duplicate': true };
}
}
return null;
};
}
At this point I get an error where I add the validator with the FormArray as an argument:
Argument of type 'AbstractControl' is not assignable to parameter of type 'FormArray'. Type 'AbstractControl' is missing the following properties from type 'FormArray': controls, at, push, insert, and 5 more.ts(2345) (property) FormGroup.controls: { [key: string]: AbstractControl; }
Can someone show me how to send a FormArray into a validator function?
Here is a Stackblitz of the validator NOT getting the FormArray
from Send a custom form control validator a FormArray
No comments:
Post a Comment