3

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Do you know how to refer to that kind of FC from this HTML template? Like lets say if formControlName="{{ i }}" how to tell if its value is dirty or something to show additional button?
nvm, I fond da wae - I'll leave this here for someone wondering about this, just like me: one can simply achieve this by calling userForm.get([i]) and use it as a condition in ngIf for instance (*ngIf="userForm.get([i]).value !== ''"). Hope this helps someone

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.