Angular `mat-table` two-way binding

1.9k views Asked by At

I have a binding issue with mat-checkbox inside a mat-table. The dataSource of the table is a basic array of objects and each object has a selected boolean property. For some reason, the two way binding is not working and selected always return false when the click event is fired.

The code is like this:

app.component.ts

   clients: Client[] = [
       { id: 1, name: `Client`, disabled: true, selected: false },
   ];

   onClientClick(client: Client) {
       console.log(client) // selected here is false
   }

app.component.html

<table mat-table [dataSource]="clients">
    <ng-container matColumnDef="client-name">
        <th mat-header-cell *matHeaderCellDef>header</th>
        <td mat-cell *matCellDef="let client">
            <mat-checkbox (click)="onClientClick(client)" [(ngModel)]="client.selected" [disabled]="client.disabled">
                {{ client.name }}
            </mat-checkbox>
        </td>
    </ng-container>
    <tr mat-row *matRowDef="let row; columns: displayedColumnsClients"></tr>
</table>

Can anyone help please?

1

There are 1 answers

0
Jaishil Bhavsar On

Create DataSource of type MatTableDataSource.

clients= new MatTableDataSource<any>([{ id: 1, name: 'Client', disabled: true, selected: false }]);

And then,

<table mat-table [dataSource]="clients">
<ng-container matColumnDef="client-name">
<th mat-header-cell *matHeaderCellDef>header</th>
<td mat-cell *matCellDef="let client">
    <mat-checkbox (click)="onClientClick(client)"
    [disabled]="client.disabled" [checked]="client.selected">
    {{ client.name }}
    </mat-checkbox>
</td>
</ng-container>
<tr mat-row *matRowDef="let row; columns: displayedColumnsClients"></tr>