I'm facing a challenge with my Angular Material dynamic table, as I am fetching data from an external database using an API. I am attempting to implement pagination on the table, but I can't seem to find suitable examples that match my scenario.
In my HTML file, I have added the mat-paginator tag to enable pagination, but I'm struggling to make it work in the .ts file where I handle the logic. Below is a snippet of my component.ts code:
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { ClientService } from '../../services/clients.service';
import { Client } from '../../domain/clients';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
export class ClientsComponent implements OnInit {
@ViewChild(MatPaginator) paginator: MatPaginator;
public displayedColumns: string[] = ['name'];
public client: Client;
public clients: Client[];
constructor(
public fb: FormBuilder,
private clientService: ClientService
) { }
ngOnInit() {
this.getClients();
}
getClient() {
this.clientService.list()
.subscribe(clients => this.clients = clients);
}
}
And here is the component.html file:
<div class="title">Customers</div>
<mat-divider></mat-divider>
<div fxLayout="column" fxLayoutGap="10px" class="m-3">
<mat-card class="mat-elevation-z8">
<mat-table [dataSource]="clients">
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
<mat-cell *matCellDef="let clients; let i = index">
<mat-form-field floatLabel="never" [appearance]="editIndex != i ? 'none' : 'legacy'">
<input matInput placeholder="{{clients.name}}" [(ngModel)]="clients.name" [readonly]="editIndex!=i">
</mat-form-field>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let col; columns: displayedColumns;"></mat-row>
</mat-table>
<mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>
</mat-card>
</div>