1 year ago
#379496
Daniel Hann
Angular Material Table shows no rows until i click to sort or use pagination
Im a bit baffled, im retrieving data from my Spring Boot back end to populate into an angular material table but for whatever reason the rows do not display until i use sorting or change pagination. I get the sense im missing something obvious, any help is appreciated.
datasource.ts
import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';
import { ParkingService } from 'src/app/services/parking.service';
// TODO: Replace this with your own data model type
export interface ParkingBuildingTableItem {
building_name: string;
postcode: string;
owner_name: string;
}
// TODO: replace this with real data from your application
const EXAMPLE_DATA: ParkingBuildingTableItem[] = [
// { building_name: 'Rohanhaven', postcode: 'SA1 6BS', owner_name: 'Nikolaus, Buckridge and Marvin' },
// { building_name: 'Port Garfield', postcode: 'SA1 6BS', owner_name: 'MacGyver, Schneider and Bosco' },
// { building_name: 'Port Loveside', postcode: 'SA1 6BS', owner_name: 'Considine, Schimmel and Abernathy' },
];
/**
* Data source for the ParkingBuildingTable view. This class should
* encapsulate all logic for fetching and manipulating the displayed data
* (including sorting, pagination, and filtering).
*/
export class ParkingBuildingTableDataSource extends DataSource<ParkingBuildingTableItem> {
data: ParkingBuildingTableItem[] = []
paginator: MatPaginator | undefined;
sort: MatSort | undefined;
constructor(private parkingService: ParkingService) {
super();
this.parkingService.getBuildings().subscribe((x) => {
this.data = x;
console.log(this.data);
});
}
/**
* Connect this data source to the table. The table will only update when
* the returned stream emits new items.
* @returns A stream of the items to be rendered.
*/
connect(): Observable<ParkingBuildingTableItem[]> {
if (this.paginator && this.sort) {
// Combine everything that affects the rendered data into one update
// stream for the data-table to consume.
return merge(observableOf(this.data), this.paginator.page, this.sort.sortChange)
.pipe(map(() => {
return this.getPagedData(this.getSortedData([...this.data]));
}));
} else {
throw Error('Please set the paginator and sort on the data source before connecting.');
}
}
/**
* Called when the table is being destroyed. Use this function, to clean up
* any open connections or free any held resources that were set up during connect.
*/
disconnect(): void { }
/**
* Paginate the data (client-side). If you're using server-side pagination,
* this would be replaced by requesting the appropriate data from the server.
*/
private getPagedData(data: ParkingBuildingTableItem[]): ParkingBuildingTableItem[] {
if (this.paginator) {
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
return data.splice(startIndex, this.paginator.pageSize);
} else {
return data;
}
}
/**
* Sort the data (client-side). If you're using server-side sorting,
* this would be replaced by requesting the appropriate data from the server.
*/
private getSortedData(data: ParkingBuildingTableItem[]): ParkingBuildingTableItem[] {
if (!this.sort || !this.sort.active || this.sort.direction === '') {
return data;
}
return data.sort((a, b) => {
const isAsc = this.sort?.direction === 'asc';
switch (this.sort?.active) {
case 'building_name': return compare(a.building_name, b.building_name, isAsc);
case 'postcode': return compare(a.postcode, b.postcode, isAsc);
case 'owner_name': return compare(a.owner_name, b.owner_name, isAsc);
default: return 0;
}
});
}
}
/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a: string | number, b: string | number, isAsc: boolean): number {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
component.ts
import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTable } from '@angular/material/table';
import { ParkingBuildingTableDataSource, ParkingBuildingTableItem } from './parking-building-table-datasource';
import { ParkingService } from 'src/app/services/parking.service';
@Component({
selector: 'app-parking-building-table',
templateUrl: './parking-building-table.component.html',
styleUrls: ['./parking-building-table.component.scss']
})
export class ParkingBuildingTableComponent implements AfterViewInit {
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
@ViewChild(MatTable) table!: MatTable<ParkingBuildingTableItem>;
dataSource: ParkingBuildingTableDataSource;
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['building_name', 'postcode', 'owner_name'];
constructor(parkingService: ParkingService) {
this.dataSource = new ParkingBuildingTableDataSource(parkingService);
}
ngAfterViewInit(): void {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
this.table.dataSource = this.dataSource;
}
}
The HTML
<div class="mat-elevation-z8 data-table">
<table mat-table class="full-width-table" matSort aria-label="Elements">
<!-- Owner Column -->
<ng-container matColumnDef="owner_name">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Owner</th>
<td mat-cell *matCellDef="let row">{{row.owner_name}}</td>
</ng-container>
<!-- Postcode Column -->
<ng-container matColumnDef="postcode">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Postcode</th>
<td mat-cell *matCellDef="let row">{{row.postcode}}</td>
</ng-container>
<!-- Building Name Column -->
<ng-container matColumnDef="building_name">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Building Name</th>
<td mat-cell *matCellDef="let row">{{row.building_name}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator #paginator [length]="dataSource?.data?.length" [pageIndex]="0" [pageSize]="10"
[pageSizeOptions]="[5, 10, 20]" aria-label="Select page">
</mat-paginator>
</div>
Before i sort or change pagnation
After i sort or change pagnation
Snapshot of the console
angular
material-table
0 Answers
Your Answer