-1

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>
bigb055
  • 198
  • 3
  • 14

2 Answers2

0

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)
}
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
0

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>
axl-code
  • 2,192
  • 1
  • 14
  • 24
  • I get Can't bind to '*ngIf' since it isn't a known property of 'mat-error'. – bigb055 Feb 12 '20 at 10:20
  • That error is because mat-error component is not importing CommonModule in its module declaration. Try to put the *ngIf in a ng-container which surrounds mat-error instead of the mat-error component – axl-code Feb 12 '20 at 10:41
  • Same result: "Can't bind to '*ngIf' since it isn't a known property of 'ng-container'" – bigb055 Feb 12 '20 at 11:04
  • Then add CommonModule to your module because it's your application where it is missing – axl-code Feb 12 '20 at 11:24