lundi 12 juillet 2021

How to add checkboxes to dynamically generated table in Angular Material?

In my component.ts I have the following:

public tableColumns: Set<Column>; // Column contains 'id' and 'name'
public tableColumnIds: Set<string>; // Set of IDs only
public dataSource: any[];

component.html:

<mat-table [dataSource]="dataSource">
  <ng-container *ngFor="let column of tableColumns" [matColumnDef]="column.id">
    <mat-header-cell *matHeaderCellDef mat-sort-header></mat-header-cell>
    <mat-cell *matCellDef="let element">  </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="tableColumnIds; sticky: true"></mat-header-row>
  <mat-row *matRowDef="let row; columns: tableColumnIds;"></mat-row>
</mat-table>

Example of the objects:

columns = [
  {
    "id": "firstname",
    "name": "First name"
  },
  {
    "id": "lastname",
    "name": "Last name"
  },
  {
    "id": "age",
    "name": "Age"
  }
]




columnsIds = ['firstname', 'lastname', 'age']




dataSource = [
      {
        "firstname": "John",
        "lastname": "Doe"
        "age": 20
      },
      {
        "firstname": "Jim",
        "lastname": "Smith"
        "age": 30
      },
      
    ]

How can I add a column with checkboxes which will allow me to select the rows? I also need a checkbox in a header to select/deselect all rows. I want to have it exactly the same as on following stackblitz: Table with selection




Aucun commentaire:

Enregistrer un commentaire