Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular : set reactive form with dynamic looping inputs

I've to set reactive form validation for a form where the inputs are made with data looping :

my form builder would look like this :

constructor(private formBuilder: FormBuilder) { 
    this.userForm = this.formBuilder.group({
      'inputOne': ['', [Validators.required]],
      'inputOne': ['', [Validators.required]],
       ...
      'inputN': ['', [Validators.required]]
    });
  }

and my template would look like this :

<form [formGroup]="userForm">
  <div class="form-group" *ngFor="let item of items; let i=index;">
        <label for="lastName">{{item.name}}</label>
        <input class="form-control" name="lastName" id="lastName" type="text" [formControlName]="item.name">
      </div>
</form>

where items are loaded dynamically from my my backend

How to populate controls dynamically in Angular reactive forms?

like image 236
firasKoubaa Avatar asked Mar 02 '26 03:03

firasKoubaa


1 Answers

sounds like you want a form array here, not a group...

  constructor(private formBuilder: FormBuilder) { 
    // build an empty form array
    this.userForm = this.formBuilder.array([]); 
  }

  // call this whenever you need to add an item to your array
  private addItem(item) {
    // build your control with whatever validators / value
    const fc = this.formBuilder.control(i.lastName, [Validators.required]);
    this.userForm.push(fc); // push the control to the form
  }

  // call this function whenever you need to reset your array
  private resetFormArray(items) {
    this.userForm.clear(); // clear the array
    items.forEach(i => this.addItem(i)); // add the items
  }

<form [formGroup]="userForm">
  <div class="form-group" *ngFor="let item of items; let i=index;">
    <label for="lastName">{{item.name}}</label>
    <input class="form-control" name="lastName" id="lastName" type="text" [formControlName]="i">
  </div>
</form>

notice you're using the index for the form control name here

like image 144
bryan60 Avatar answered Mar 03 '26 15:03

bryan60



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!