I’m working with Angular 18 and use angular material. I build preview component with dynamic talbe, so any json that comes from parent table should be places as table. But my pagination doesn’t work.
component.ts
export class PreviewComponent implements OnChanges, AfterViewInit, OnInit {
@Input() data: any[] = [];
displayedColumns: string[] = [];
dataSource: MatTableDataSource<any> = new MatTableDataSource();
@ViewChild(MatPaginator) paginator!: MatPaginator;
ngOnInit(): void {}
ngOnChanges(): void {
if (this.data.length > 0) {
this.displayedColumns = Object.keys(this.data[0]);
this.dataSource.data = this.data;
} else {
this.dataSource.data = [];
}
this.connectPaginator();
}
ngAfterViewInit(): void {
this.connectPaginator();
}
connectPaginator() {
if (this.dataSource && this.paginator) {
this.dataSource.paginator = this.paginator;
}
}
}
component.html
<div class="mat-elevation-z8 preview-container">
<div *ngIf="dataSource && dataSource.data.length > 0; else noDataTemplate">
<table mat-table [dataSource]="dataSource" class="mat-table">
<ng-container *ngFor="let column of displayedColumns" [matColumnDef]="column">
<th mat-header-cell *matHeaderCellDef> {{ column }} </th>
<td mat-cell *matCellDef="let element"> {{ element[column] }} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator [pageSizeOptions]="[10, 20]" showFirstLastButtons></mat-paginator>
</div>
<ng-template #noDataTemplate>
<div class="no-data-message-container">
<p class="no-data-message">There is no data yet!</p>
</div>
</ng-template>
</div>
I tried to set paginator explicitly. Used different types of view init constructors.
New contributor
Volodymyr Hula is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.