In Angular 8, We can easily achieve multiple/single material table sorting and paging inside *ngIf. In the below example I am using "ng-template" in order to show/hide the table using *ngIf else.
My Sample *ngIf format
<div *ngIf="!isDataLoadedFromApi; else loadTransactions">No data to display</div>
Below tables are in the same form
Table-1
<ng-template #loadCases>
<table mat-table [dataSource]="snowDataSource" #snowSort="matSort" matSort class="mat-elevation-z3 snow-table">
<mat-paginator class="mat-elevation-z3" #snowPaginator [pageSizeOptions]="[3, 10, 20]" showFirstLastButtons>
</mat-paginator></ng-template>
Table-2
<ng-template #loadTransactions>
<table mat-table [dataSource]="transactionDataSource" #transactionSort="matSort" matSort
class="mat-elevation-z3 transaction-table">
<mat-paginator class="mat-elevation-z3" #transactionPaginator [pageSizeOptions]="[3, 10, 20]"
showFirstLastButtons>
</mat-paginator></ng-template>
Check the "#transactionSort="matSort" and #transactionPaginator in Table-2.
Also "#snowSort="matSort" and #snowPaginator in Table-1
In the TS file configure view child and other settings like below. That's it.
@ViewChild('snowSort', { static: false }) set matSnowSort(snowSort: MatSort) {
this.snowSort = snowSort;
if (this.snowDataSource !== null && this.snowDataSource !== undefined) {
this.snowDataSource.sort = this.snowSort;
}}
@ViewChild('snowPaginator', { static: false }) set matSnowPaginator(snowPaginator: MatPaginator) {
this.snowPaginator = snowPaginator;
if (this.snowDataSource !== null && this.snowDataSource !== undefined) {
this.snowDataSource.paginator = this.snowPaginator;
}}
@ViewChild('transactionSort', { static: false }) set matTransactionSort(transactionSort: MatSort) {
this.transactionSort = transactionSort;
if (this.transactionDataSource !== null && this.transactionDataSource !== undefined) {
this.transactionDataSource.sort = this.transactionSort;
}}
@ViewChild('transactionPaginator', { static: false }) set matTransactionPaginator(transactionPaginator: MatPaginator) {
this.transactionPaginator = transactionPaginator;
if (this.transactionDataSource !== null && this.transactionDataSource !== undefined) {
this.transactionDataSource.paginator = this.transactionPaginator;
}}
private transactionSort: MatSort;
private transactionPaginator: MatPaginator;
private snowSort: MatSort;
private snowPaginator: MatPaginator;
payIdTransactions: TLItem[];
snowCases: Cases[];
transactionDataSource: MatTableDataSource<TLItem>;
snowDataSource: MatTableDataSource<Cases>;
private getTransactions(startDate: string, endDate: string) {
this.payIdTransactions = results.getTransactionsResponse.TLItems.TLItem;
this.transactionDataSource = new MatTableDataSource(this.payIdTransactions);
}
private getSnowCases(startDate: string, endDate: string) {
this.snowCases = results.getCasesResponse.cases;
this.snowDataSource = new MatTableDataSource(this.snowCases);
}