import { NgTemplateOutlet } from '@angular/common'; import { AfterViewInit, Component, computed, effect, input, output, signal, TemplateRef, viewChild, } from '@angular/core'; import { MatSort, MatSortModule, Sort, SortDirection, } from '@angular/material/sort'; import { MatTableDataSource, MatTableModule } from '@angular/material/table'; import { Router } from '@angular/router'; export interface BaseColumn { id: string; header: string; type: 'accessor' | 'display' | 'group'; cellTemplate?: TemplateRef; } export interface AccessorColumn extends BaseColumn { type: 'accessor'; accessorKey: keyof T; } export interface DisplayColumn extends BaseColumn { type: 'display'; } export type GenericColumn = AccessorColumn | DisplayColumn; @Component({ selector: 'app-data-table', standalone: true, imports: [MatTableModule, NgTemplateOutlet, MatSortModule], templateUrl: './data-table.component.html', styleUrl: './data-table.component.scss', }) export class DataTableComponent implements AfterViewInit { data = input.required(); columns = input.required[]>(); filterTerm = input(''); detailTemplate = input | null>(null); expandedElement = signal(null); maxHeight = input(null); containerOverflow = computed(() => (this.maxHeight() ? 'auto' : 'visible')); stickyHeader = input(true); activeSortKey = input(''); sortDirection = input(''); navigatePrefix=input(''); navigateField=input(''); sortChange = output(); displayedColumns = computed(() => this.columns().map((col) => col.id)); dataSource = new MatTableDataSource([]); sort = viewChild.required(MatSort); constructor(private router:Router) { effect(() => { const currentData = this.data(); this.dataSource.data = currentData; this.dataSource.filterPredicate = (data: T, filter: string) => { const columnsToSearch = this.columns() .filter((col): col is AccessorColumn => col.type === 'accessor') .map((col) => col.accessorKey); return columnsToSearch.some((key) => { const value = data[key]; return value ? String(value).toLowerCase().includes(filter) : false; }); }; this.dataSource.filter = this.filterTerm().trim().toLowerCase(); }); effect(() => { const matSortInstance = this.sort(); const activeKey = this.activeSortKey(); const direction = this.sortDirection(); if ( matSortInstance.active !== activeKey || matSortInstance.direction !== direction ) { matSortInstance.active = activeKey; matSortInstance.direction = direction; this.dataSource.sort = matSortInstance; } }); } ngAfterViewInit(): void { this.dataSource.sort = this.sort(); } onSortChange(sort: Sort) { this.sortChange.emit(sort); } navigateToDataField(row: any): void { if (!this.navigatePrefix() || !this.navigateField()) { return; } const value = row[this.navigateField()]; if (value != null) { this.router.navigate([this.navigatePrefix(), value]); } } toggleRow(row: T): void { if (!this.detailTemplate()) return; this.expandedElement.update((current) => (current === row ? null : row)); } }