I'm using Angular 6 with reactive forms. One of the form field is a FormArray which adds controls as the user clicks an Add button.
Within the FormArray, I would like to check whether the FormControl value already exists in the FormArray.
This works fine until the user clicks 'Add' button which resets the previous control error and marks the control as valid although it still has a duplicate value.
This is the function to add control in the form array:
onAddIPAddress() {
if (( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).length < 8) {
const control = new FormControl(null, Validators.compose([
Validators.required,
Validators.pattern(this.ipaddressPattern),
this.forbiddenIPs.bind(this),
this.onDuplicateIPFormArray.bind(this)
]));
( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).push(control);
} else {
return;
}
}
Then, this is the custom validator code:
onDuplicateIPFormArray(control: FormControl): {
[s: string]: boolean
} {
if (
( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).length > 1 &&
!( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).value.includes(null) &&
( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).value.indexOf(control.value) !== -1)
{
console.log(( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).value.indexOf(control.value));
return {
duplicateIP: true
};
}
return null;
}
From the console, I can see the IndexOf value is incorrect but not able to understand why.
Any ideas how I can handle this ?
Thanks