yavg
yavg

Reputation: 3051

How can I validate an array of fields in a reactive form?

I have seen examples and I have not been able to find a way to validate my form. I basically have a form that consists of an array of fields that I want to validate because they are required.

this.formNames = this.fb.group({
  element_name: new FormControl('', [Validators.required]) //input text 
});

this.myForm = this.fb.group({
  names: this.fb.array([
      this.formNames,  
      this.formNames
  ])
})

enter image description here

I have the problem that I am trying to validate the text fields that are represented by: names and are required. but what happens in the image happens if I add text in any text field, they are all validated, I want that when I write something in the corresponding text field, validation is done exclusively for that field.

this is my live code:

https://stackblitz.com/edit/angular-xkhkoc?file=app/app.component.ts

<form [formGroup]="myForm">
  <div formArrayName="names">
  <ng-container
      *ngFor="let item of myForm.get('names').controls; let i=index">
      <div [formGroupName]="i">
              <input type="text" class="form-control" id="element_name"
                  formControlName="element_name"
                  placeholder="insert name" 
              >
              {{item.controls['element_name'].valid | json}}
      </div>
   </ng-container>
  </div>
 </form>

Upvotes: 1

Views: 1101

Answers (1)

Manuel Panizzo
Manuel Panizzo

Reputation: 896

You are using the same object to all inputs. Try this.

this.myForm = this.fb.group({
  names: this.fb.array([
    this.fb.group({ element_name: [null, [Validators.required]] }),
    this.fb.group({ element_name: [null, [Validators.required]] }),
  ])
})

Upvotes: 1

Related Questions