import { NgTemplateOutlet } from '@angular/common'; import { AfterViewInit, Component, computed, effect, inject, input, output, signal, TemplateRef, viewChild, } from '@angular/core'; import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; import { MatSort, MatSortModule, Sort, SortDirection, } from '@angular/material/sort'; import { MatTableDataSource, MatTableModule } from '@angular/material/table'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatTooltipModule } from '@angular/material/tooltip'; import { ActivatedRoute, Router } from '@angular/router'; import { SkTextDirective } from '../../../custom-directives/sk-text.directive'; export interface BaseColumn { id: string; header: string; type: 'accessor' | 'display' | 'group'; headerTemplate?: TemplateRef; 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, MatButtonModule, MatIconModule, MatTooltipModule, SkTextDirective, ], 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); canExpand = input<((row: T) => boolean) | null>(null); maxHeight = input(null); containerOverflow = computed(() => (this.maxHeight() ? 'auto' : 'visible')); stickyHeader = input(true); queryParamSortKey = input(null); queryParamSortDirectionKey = input(null); _urlSortValue = computed(() => { const params = this.queryParams(); const key = this.queryParamSortKey(); return params && key ? params[key] || null : null; }); _urlSortDirectionValue = computed(() => { const params = this.queryParams(); const key = this.queryParamSortDirectionKey(); return params && key ? params[key] || null : null; }); handleSortChange = output(); readonly expandColumnId = 'expand'; displayedColumns = computed(() => { const ids = this.columns().map((col) => col.id); return this.detailTemplate() ? [this.expandColumnId, ...ids] : ids; }); dataSource = new MatTableDataSource([]); sort = viewChild.required(MatSort); private readonly activatedRouter = inject(ActivatedRoute); private readonly router = inject(Router); private readonly queryParams = toSignal( this.activatedRouter.queryParams.pipe(takeUntilDestroyed()), ); constructor() { 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._urlSortValue(); const direction = this._urlSortDirectionValue(); if ( matSortInstance.active !== activeKey || matSortInstance.direction !== direction ) { if (activeKey == null) { matSortInstance.active = ''; } else { matSortInstance.active = activeKey; } if (direction == null) { matSortInstance.direction = ''; } else { matSortInstance.direction = direction as SortDirection; } this.dataSource.sort = matSortInstance; } }); } ngAfterViewInit(): void { this.dataSource.sort = this.sort(); } _handleSortChange(sort: Sort): void { this.handleSortChange.emit(sort); const sortKey = this.queryParamSortKey(); const sortDirectionKey = this.queryParamSortDirectionKey(); if (sortKey != null) { const queryParams: any = { [sortKey]: sort.active || null, }; if (sortDirectionKey != null) { queryParams[sortDirectionKey] = sort.direction || null; } this.router.navigate([], { queryParams, queryParamsHandling: 'merge', }); } } isExpandable(row: T): boolean { if (!this.detailTemplate()) return false; return this.canExpand()?.(row) ?? true; } toggleRow(row: T): void { if (!this.isExpandable(row)) return; this.expandedElement.update((current) => (current === row ? null : row)); } }