NgModel MatTable MatCheckBox example

July 13, 2021 · 1 min readLucian Ciobanu
Tags:AngularAngularMaterial

I'm enjoying using Angular's bananabox magic more and more and have just found another use case for NgModel.

For this specific case, I had to display data and just alow the user to modify a property between true and false so I though of using material table, material checkbox and was pleasantly surprised to see that [(ngModel)] can also be linked to the table's dataSource.data array.

<mat-table [dataSource]="dataSource">
  <ng-container matColumnDef="Inactive">
    <mat-header-cell class="d-flex justify-content-center" *matHeaderCellDef>Inactive</mat-header-cell>
    <mat-cell class="d-flex justify-content-center" *matCellDef="let outage; let i = index">
      <mat-checkbox [(ngModel)]="dataSource.data[i].Inactive"></mat-checkbox>
    </mat-cell>
  </ng-container>
</mat-table>

And that's it, really. Now the dataSource will update on checkbox change.

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery