Open OsamaAsender opened 2 months ago
Assuming You wanna add pagination to your Angular Material table,
Modular Approach
First, include MatPaginatorModule
in your module’s imports.
import { MatPaginatorModule } from '@angular/material/paginator';
@NgModule({
imports: [
// other imports
MatPaginatorModule,
],
})
export class YourModule { }
Next, in your component’s HTML file, add the mat-paginator
to your table:
<table mat-table [dataSource]="dataSource">
<!-- Define your columns here -->
<ng-container matColumnDef="fruit">
<th mat-header-cell *matHeaderCellDef> Fruit </th>
<td mat-cell *matCellDef="let element"> {{element.fruit}} </td>
</ng-container>
<ng-container matColumnDef="color">
<th mat-header-cell *matHeaderCellDef> Color </th>
<td mat-cell *matCellDef="let element"> {{element.color}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator [pageSize]="5" [pageSizeOptions]="[5, 10, 20]"></mat-paginator>
Finally, in your component’s TypeScript file, link the paginator to your table data:
import { Component, ViewChild, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
})
export class YourComponent implements OnInit {
displayedColumns: string[] = ['fruit', 'color'];
dataSource = new MatTableDataSource(ELEMENT_DATA);
@ViewChild(MatPaginator) paginator!: MatPaginator;
ngOnInit() {
this.dataSource.paginator = this.paginator;
}
}
const ELEMENT_DATA = [
{ fruit: 'Apple', color: 'Red' },
{ fruit: 'Banana', color: 'Yellow' },
// Add more data as needed
];
Standalone Component Approach
If you're using a standalone component, import MatPaginatorModule
directly into your component:
//....Rest Imports...
import { MatPaginatorModule } from '@angular/material/paginator';
@Component({
selector: 'app-standalone',
templateUrl: './standalone.component.html',
standalone: true,
imports: [MatPaginatorModule, MatTableModule]
})
export class StandaloneComponent {
//Code goes here...
}
Then similarly Add the paginator to the HTML template of your standalone component