Reputation: 308
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>
Upvotes: -1
Views: 1073
Reputation: 27232
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)
}
Upvotes: 0
Reputation: 2274
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>
Upvotes: 0