Menggunakan Angular Material Table – 2

Melanjutkan dari modul sebelumnya, kita akan menambahkan paginator pada table.

Buka file notes.component.html, tambahkan code paginator.

<div class="mat-elevation-z8">
    <table mat-table [dataSource]="dataSource">  
      <ng-container matColumnDef="position">
        <th mat-header-cell *matHeaderCellDef> No. </th>
        <td mat-cell *matCellDef="let note"> {{note.id}} </td>
      </ng-container>
  
      <ng-container matColumnDef="title">
        <th mat-header-cell *matHeaderCellDef> Title </th>
        <td mat-cell *matCellDef="let note"> {{note.title}} </td>
      </ng-container>
  
      <ng-container matColumnDef="date">
        <th mat-header-cell *matHeaderCellDef> Date </th>
        <td mat-cell *matCellDef="let note"> {{note.date | date:'yyyy-MM-dd'}} </td>
      </ng-container>
  
      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </table>

    <!-- code paginator -->
    <mat-paginator [pageSize]="2" [pageSizeOptions]="[5, 10, 20]"
                   showFirstLastButtons 
                   aria-label="Select page of periodic elements">
    </mat-paginator>
  </div>

Kemudian buka file notes.component.ts, tambahkan code implementasi untuk paginator.

import { AfterViewInit, Component, Input, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { Note } from '../../models/note';

@Component({
  selector: 'app-notes',
  templateUrl: './notes.component.html',
  styleUrls: ['./notes.component.scss']
})
export class NotesComponent implements OnInit, AfterViewInit {
  displayedColumns: string[] = ['position', 'title', 'date'];
  dataSource! : MatTableDataSource<Note>;
    
  @Input() notes! : Note[];
  
  //implementasi paginator
  @ViewChild(MatPaginator) paginator!: MatPaginator;

  constructor() { }

  ngOnInit(): void {
    this.dataSource = new MatTableDataSource<Note>(this.notes);
  }

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

Sesuai ekspektasi, kita sudah berhasil mengimplementasikan paginator.

Pada modul selanjutnya kita akan implementasikan filtering

Sharing is caring:

Leave a Comment