0

I am using angular 4 to create a custom validator in a reactive form on a FormArray item that is an array. It works on the initial load, however if i add an item to the array and then remove that item, the Validator.required validation is than not set.

FromArray -> FormGroup

let customItemsValidator: Array<any> = item.selectType === 'custom' && item.required ? 
                                       [Validators.required] : [];

return this.formBuilder.group({
   customItems: [[], customItemsValidator],
})

main form on the main component.ts

this.appForm = this.formBuilder.group({
   option: this.formBuilder.array([]),
   items: this.formBuilder.array([])
});

So i can build the form and it works 100%, i have a submit button that is disabled if the form is not valid and on the initial load the button stays disabled until i add an item to the customItems property. Once i remove the added item the submit button is still enabled even though now it should be disabled because it is required and has no value.

the remove method

selectOptionsCustomRemove(customItem, customIdx: number, idx: number) {
  pullAt(this.items.at(idx).get('customItems').value, customIdx);
}

So it removes the item but the validity does not change on the form.

I have tried with the updateValueAndValidity() after the pullAt but this does not work seem to work.

1 Answers1

0

Turns out when i removed the item from the array it just left an empty [] because the pullAt just removed from the index, which left the property with a value of []. So i had to assign the array to null so that the validation would trigger.

if (this.options.at(idx).get('customItems').value.length === 0) { 
        this.options.at(idx).patchValue({ customItems: null }) 
}