I am trying to update the data source, and while the data shows up it doesn't apply any sorting or pagination that has been setup.
Note: I used the table schematic from angular material as base before making changes.
TS
export class DummyTableComponent {
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
@ViewChild(MatTable) table!: MatTable<any>;
items$!: Observable<any>;
dataSource: MatTableDataSource<any>;
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['title', 'status'];
constructor(private http: HttpClient) {
this.dataSource = new MatTableDataSource<any>();
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator;
this.items$ = this.http.get<any>(environment.apiUrl "/items)
.pipe(
map((retval: any) => retval.items),
tap(retval => {
this.dataSource.data = retval;
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator;
})
);
}
}
HTML
<div *ngIf="items$ | async">
<table mat-table matSort [dataSource]="dataSource">
<ng-container matColumnDef="title">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Title </th>
<td mat-cell *matCellDef="let element"> {{element.title}} </td>
</ng-container>
<ng-container matColumnDef="status">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Status </th>
<td mat-cell *matCellDef="let element"> {{element.status}} </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]="[1,5, 10, 20]"
aria-label="Select page">
</mat-paginator>
</div>
Essentially data gets loaded into table, but that is it. No sorting or pagination works.
CodePudding user response:
Because you are using *ngIf="items$ | async"
no child components are rendered yet. So, MatSort
and MatPaginator
are undefined in the tap
operator.
You could wrap it with setTimeout
(to let them render first) or use [hidden]="(items$ | async) === null"
instead of *ngIf
.