Friday 21 September 2018

Adding Paginator to Angular Material Table

To add paging feature of pre-fetched data to Angular Material 6 Table:
- on html page add mat-paginator to the bottom (or top) of the table:
<mat-paginator [pageSizeOptions]="[2, 5, 10]"></mat-paginator>

- on module page (e.g., module.ts):
//import MatPaginatorModule
import { MatPaginatorModule } from '@angular/material/paginator';
@NgModule({
  . . .,
  imports: [
    . . .
    MatPaginatorModule
  ],
. . .
})

- on component page (e.g., component.ts):
// import ViewChild, MatPaginator and MatTableDataSource
import { ViewChild } from '@angular/core';
import { MatPaginator, MatTableDataSource } from '@angular/material';

export class AppComponent implements AfterViewInit, OnInit{

  . . .

  dataSource : MatTableDataSource<MyDataModel>;

  @ViewChild(MatPaginator) paginator: MatPaginator;

  ngAfterViewInit() {
    // set datasource paginator
    this.dataSource.paginator = this.paginator;
  }

  ngOnInit() {
    // initialise the datasource
    this.dataSource = new MatTableDataSource<MyDataModel>(MY_DATA);
  }
}

I will create a post of how to do paging and sorting with server-side data interaction soon.


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.