Reputation: 665
I am using dynamic form control to create dynamic fields
by using reference of https://www.c-sharpcorner.com/blogs/creating-form-controls-dynamically-in-angular-7-project
I want to validate dynamic fields using setValidators
and updateValueAndValidity
in Angular 6.
Below is syntax I have used but it's not working.
(<FormArray>this.addQuestionForm.get('other')).setValidators([Validators.required]);
(<FormArray>this.addQuestionForm.get('other')).updateValueAndValidity();
Also let me know how to delete dynamically added field with reference of "<FormArray>this.addQuestionForm.get('other')
"
Thanks
Upvotes: 0
Views: 235
Reputation: 680
You have to make a loop on each control of (this.addQuestionForm.get('other')) and apply validation on each component
(<FormArray>this.addQuestionForm.get('other')).controls.forEach((control) => {
control.setValidators([Validators.required]);
control.updateValueAndValidity();
});
If you want to delete dynamically added field in formArray, then you have to get index of element you want to delete
As FormArray class has removeAt which takes the index. If you do not know the index, you can do a workaround:
this.addQuestionForm.get('other').removeAt(index);
Upvotes: 1
Reputation: 612
I think the problem here is setting a required validation on FormArray
. Because in JavaScript an empty array is also true.
What you can do is set a minLength
validation on the FormArray
field.
Let me know if this works.
Upvotes: 0