0

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

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Kinjal, I have tried above given code it works for "removeAt" but not for apply validation on each component. Please suggest another way. Thanks
0

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.

1 Comment

Hi Himanshu Mittal, I have tried by minLength validation but it not worked for me. Please suggest another way. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.