mat-input not working properly in mat-table Angular 8

2.2k Views Asked by At

I'm facing issue in mat-table, my input field is not working properly inside table. All rows are using one input field. Means if I type text inside the input box, all rows showing that text

my code:

<ng-container matColumnDef="Remarks">
    <mat-header-cell *matHeaderCellDef>scheduled hours</mat-header-cell>
    <mat-cell *matCellDef="let element">  
        <mat-form-field>
            <input matInput [(ngModel)]="Remarks" (input)="$event.target.value.length > 2 && Remarks($event.target.value)"  name="AppRemarks"  #AppRemarks="ngModel"  placeholder="Remarks"> &nbsp; &nbsp;
        </mat-form-field> 
    </mat-cell>
</ng-container>
3

There are 3 best solutions below

1
On

I ran into this as well! Ended up being the name attribute throwing things off. name is used to uniquely identify the control, so when you apply the same name to each attribute they all share the same identifier/key and get treated as one input.

This should solve your issue (left some code out for brevity):

<ng-container matColumnDef="Remarks">
    <mat-header-cell *matHeaderCellDef>scheduled hours</mat-header-cell>
    <mat-cell *matCellDef="let element; let i = index;">  
        <mat-form-field>
            <input matInput [(ngModel)]="Remarks" name="AppRemarks{{ i }}">
        </mat-form-field> 
    </mat-cell>
</ng-container>
0
On

Hi there its not the fault of the mat table you are making a table out of the same variable and each row has two way binding for the same variable this will result in the each row will have the same value.

In order to achive what you wanted please take a look at Angular Reactive formarrays.

Here is a pretty good tutorialhow to use formarrays https://netbasal.com/angular-reactive-forms-the-ultimate-guide-to-formarray-3adbe6b0b61a

0
On

It should be [(ngModel)]="AppRemarks" since name= "AppRemarks" in your Input field