I have a custom table component(MatTable) and my columns are passed by ng-content, but when I try change MatSort, my table doesn’t update…
My table component HTML :
<div class="table-container">
<table
mat-table
matSort
[dataSource]="data"
matSortActive="created"
matSortDisableClear
matSortDirection="desc"
>
<ng-content select="[columns]"></ng-content>
<tr
mat-header-row
*matHeaderRowDef="displayedColumns"
></tr>
<tr
mat-row
*matRowDef="let row; columns: displayedColumns"
></tr>
<tr
class="mat-row"
*matNoDataRow
>
<td
*ngIf="!loadingData"
class="mat-cell no-data"
[attr.colspan]="data"
>
<p class="no-data-text">{{ noDataMessage }}</p>
</td>
</tr>
</table>
</div>
<mat-paginator
[pageSize]="20"
showFirstLastButtons
[length]="totalResults"
></mat-paginator>
</div>
Table component TypeScript file :
import {
Component,
ViewChild,
AfterViewInit,
AfterContentInit,
Input,
Output,
EventEmitter,
ContentChildren,
QueryList,
} from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatColumnDef, MatTable } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
import { BreakpointObserverService } from '@ndd-averba/shared/services';
import { ITablePaginator } from '@ndd-averba/shared/interfaces';
@Component({
selector: 'ndd-averba-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.scss'],
})
export class TableComponent<T> implements AfterViewInit, AfterContentInit {
@Input() public displayedColumns!: string[];
@Input() public data!: Array<T>;
@Input() public loadingData!: boolean;
@Input() public noDataMessage!: string;
@Input() public totalResults!: number;
@Output() public loadDataEvent!: EventEmitter<ITablePaginator>;
@ContentChildren(MatColumnDef) columnDefs!: QueryList<MatColumnDef>;
@ViewChild(MatTable, { static: true }) table!: MatTable<T>;
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort, { static: false }) sort!: MatSort;
constructor(protected breakpointObserverService: BreakpointObserverService) {
this.loadDataEvent = new EventEmitter();
}
ngAfterContentInit(): void {
this.columnDefs.forEach((columnDef) => {
this.table.addColumnDef(columnDef);
});
}
ngAfterViewInit(): void {
this.sort.sortChange.subscribe(() => (this.paginator.pageIndex = 0));
this.loadDataEvent.emit({
sort: this.sort,
paginator: this.paginator,
});
}
}
I have another component that use this table and pass columns by ng-content. It receive EventEmitter from table component to render data from API. Can anybody help me?