0

I am creating dynamic FormArray and FormGroups. In which I am creating formControl with .addControl(). How Do I add validations for controls, which can be required, phone number, email, etc.

Mayuri More
  • 216
  • 2
  • 12
  • 1
    Paste your code. – Ammar Hussain Jul 22 '19 at 04:51
  • Data can be either array of objects or single object if (Array.isArray(this.resumeSections[curr].data)) { if (!this.form.get(curr)) { this.form.addControl(curr, this.fb.array([])); } const arr = this.form.get(curr) as FormArray; this.resumeSections[curr].data.forEach((datum) => arr.push( this.fb.group(datum))); } else { if (!this.form.get(curr)) { this.form.addControl(curr, this.fb.group(this.resumeSections[curr].data)); } } – Mayuri More Jul 22 '19 at 05:02
  • 1
    You can use setValidators to add validator to the control. Please refer to this link. https://stackoverflow.com/questions/49075027/angular-dynamically-add-remove-validators – Andrew Rayan Jul 22 '19 at 05:02
  • @MayuriMore, I edited your question to add the code in your comment – Eliseo Jul 22 '19 at 06:41
  • 1
    when you create the FormControl, you can add the validator too -this.fb.group allow add not only the value else the validators. If is a formControl, simply this.fb.control(value,validator), if is a formGroup, in Angular 8 is this.fb.group(value,{validator:Validator}), see the docs https://angular.io/api/forms/FormBuilder#group and see that in case of control the second argument is `ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]` but in a formgroup the second argument is `AbstractControlOptions| | { [key: string]: any; } = null` – Eliseo Jul 22 '19 at 06:46

1 Answers1

0

You can use setValidators([Validators.required]) and every other validation you might want to add.

S.Voulgaris
  • 184
  • 1
  • 4