I have a Formgroup with a Formarray inside.
This is the structure:
myForm = this.fb.group(
{
title: ["", [Validators.required, Validators.minLength(4)]],
pairs: this.fb.array(
this.fPairs.map(f =>
this.fb.group({
grade: [],
value: []
})
)
)
}
);
my FormArray that gets mapped, looks like this onInit:
fPairs: Array<pairs> = [
{grade: 0, value: 0},
{grade: 0, value: 0},
{grade: 0, value: 0},
{grade: 0, value: 0}
];
What I want to achieve, as every property of each object of this FormArray is an input field in my form, I need a validation that does this:
The object properties at index 0, must have BIGGER values than the next index.
so in myForm,
pairs[0].score > pairs[1].score
pairs[1].score > pairs[2].score
pairs[2].score > pairs[3].score
same goes for the property "value".
How can I correctly implement a real validator (type ValidatorFn) for this formArray?
So far I only managed to create a function, that checks for each field, compares it with the previous and the next, if the values are not following the rules, I manually set an error with setErrors()
This function is in ValueChanges() subscription, so when a value in that formArray changes, it checks it with my function
Is there a better way?
Here a stackblizt (the valueChanges subscription doesn't work properly, it will refresh only when writing in the next field, you ll see what I mean in the stackblitz)
https://stackblitz.com/edit/angular-mat-formfield-flex-layout-x9nksb
thank you