Tuesday, 4 September 2018

How to Add Angular Material Table

Quick reference of how to add Angular Material Table (Angular Material 6):
- on module page (e.g., module.ts):
// import the module
import { MatTableModule } from '@angular/material';
@NgModule({
  . . .,
  imports: [
    . . .
    MatTableModule
  ],
 . . .
})

- on component page (e.g., component.ts):
export class AppComponent implements AfterViewInit, OnInit{
  . . .
// specify columns to be displayed
  displayedColumns : string[] = ['columnone', 'columntwo'];

// specify data to be displayed
  dataSource = [{columnone: 1, columntwo: ‘A’},{columnone: 2, columntwo: ‘B’},…]
  . . .
}

- on html page:
<table mat-table [dataSource]="dataSource">
  <ng-container matColumnDef="columnone">
    <th mat-header-cell *matHeaderCellDef> ColumnOne </th>
    <td mat-cell *matCellDef="let elem"> {{elem.columnone}} </td>
  </ng-container>

  <ng-container matColumnDef="columntwo">
    <th mat-header-cell *matHeaderCellDef> ColumnTwo </th>
    <td mat-cell *matCellDef="let elem"> {{elem.columntwo}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

We will see how to add Angular Material Paginator on the next post.

No comments: