0

Is it possible to add property dynamically to groupform? I need a property name to have an index as part of the name

createForm() {
    for (let index = 0; index < 10; index++) {
        this.groupForm = this.fb.group({
            prixName+index: ['', [Validators.maxLength(4)]],
        });


    }
}
Happy Coder
  • 1,293
  • 1
  • 19
  • 35

1 Answers1

0

Use addControl function for this

this.testForm.addControl('new', new FormControl('', Validators.required));

see this answer addControl to FormGroup dynamically in Angular and this link too https://angular.io/api/forms/FormGroup#addcontrol

createForm() {
   this.groupForm = this.fb.group({});
   for (let index = 0; index < 10; index++) {
     this.groupForm.addControl(prixName+index, new FormControl(null, Validators.maxLength(4)));

   }
}

If you need form control array then use FormArray instead of index or increment counter. This will also helps you in that case https://angular.io/api/forms/FormArray

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
khushi
  • 178
  • 2
  • 10