Access form group control inside *ngFor

960 views Asked by At

In the template file I'm iterating over an array of elements and for each element a separate row is inserted.

Each element has the same set of controls, but whenever I enter a wrong value inside one of the input fields the same error message appears on all other input controls. I need it to validate only the current input field.

Hope I explained it clearly. Below is my template code:

<tr *ngFor="let element of elements">
  <td>
      <input matInput
             formControlName="elementNamePrefix"
             [required]="controls.elementNamePrefix.required"
             [placeholder]="controls.elementNamePrefix.displayName"
             [type]="controls.elementNamePrefix.type">
      <mat-error *ngIf="group.get('elementNamePrefix').hasError('maxlength')">
        Max length is XY characters!
      </mat-error>
  </td>
</tr>
2

There are 2 answers

2
Rohìt Jíndal On

As per my understanding parts is a formArray. Hence, you have to find the formGroup based on that index to display the error message in that particular control.

Try this condition in <mat-error> container.

<tr *ngFor="let part of parts; let i=index">
  <td>
      <input matInput
             formControlName="partNamePrefix"
             [required]="controls.partNamePrefix.required"
             [placeholder]="controls.partNamePrefix.displayName"
             [type]="controls.partNamePrefix.type">
    <mat-error *ngIf="getFormGroup(i).get('partNamePrefix').hasError('maxlength')">
        Max length is XY characters!
    </mat-error>
  </td>
</tr>

TS :

getFormGroup(index: number) {
  return (this.parts.controls.find((_controls, groupIndex) => (groupIndex === index)) as FormGroup)
}
4
axl-code On

I think the problem is related with the way you declare the input. You are using the same formControlName for all of them. Instead of it try to assign a dynamic one:

<tr *ngFor="let part of parts; index as i">
  <td>
    <input matInput
         formControlName="{{part.whatever}}"
         [required]="controls.partNamePrefix.required"
         [placeholder]="controls.partNamePrefix.displayName"
         [type]="controls.partNamePrefix.type">
    <mat-error *ngIf="group.get({{part.whatever}}).hasError('maxlength')">
      Max length is XY characters!
    </mat-error>
  </td>
</tr>