I have a mat table in where Im getting values from backend and displaying. Now Im trying to add a new typeable field "cmnts", where it should be a text field and have validations. My issue here is validation is applying to every row & whatever text im entering in the first row , that is appearing in all the rows. Is my form control name should be unique for each row. In that case how should i use in ts file. Could you please suggest?
My html code is like below:
<table mat-table [dataSource]="dataSource" class="" matSort >
<tbody>
<th><td>...</td></th>
<ng-container matColumnDef="cmts">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Comments
</th>
<form [formGroup]="commentsForm" >
<td mat-cell *matCellDef="let element">
<span *ngIf="element?.id=='321'">
<mat-form-field>
<input matInput id="cmnts" formControlName="cmnts" required>
<mat-error *ngIf="submitted || h.cmnts.errors || h.cmnts.touched">
<span *ngIf="h.cmnts.errors?.required">cmnts is Required</span>
</mat-error>
<mat-error *ngIf="submitted || h.cmnts.errors">
<span *ngIf="h.cmnts.errors?.minlength"> Minimum length should be 10</span>
</mat-error>
<mat-error *ngIf="submitted || h.cmnts.errors">
<span *ngIf="h.cmnts.errors?.maxlength"> Maximum length should be 30 </span>
</mat-error>
</mat-form-field>
</span>
</td>
</form>
</ng-container>
My Ts file :
commentsForm: FormGroup;
this.commentsForm = this.fb.group({
cmnts: ['', [Validators.required,Validators.minLength(10), Validators.maxLength(40)]],
})
get h() { return this.commentsForm.controls; }
I have tried using formArray as below also. still unable to set validations separtely for each row. Please suggest. //Updated
<form [formGroup]="CmntsForm" >
<td mat-cell *matCellDef="let element;let rowIndex = index">
<span *ngIf="element?.sts=='A'">
<mat-form-field>
<input matInput id="cmnts" formControlName="cmnts" required>
</mat-form-field>
</span>
</td>
ts:
this.CmntsForm = this.fb.group({
cmnts: this.fb.array( ['', [Validators.required,Validators.minLength(1), Validators.maxLength(30)]])
})
get cmnts(){
return this.CmntsForm.controls["cmnts"] as FormArray;
}
You need to configure form array of form group with own validation rules for each row. Here is an example with the latest version of angular hope it helps.
HTML:
TS: