Hi
I am trying to create Dynamic table using Angular Material. What should be the Html Code. Using ANgular 17
Code
TypeScript
export class DynamicMatTableComponent implements OnInit,AfterViewInit,OnChanges {
@Input() title?: string;
@Input() tabelData: any = [];
@Input() columnArray: string [] = [];
@Input() columns: any = [];
@Input() actionColumn: any = [];
@Input() permission: any;
dataSource: MatTableDataSource;
constructor(private cdr: ChangeDetectorRef) {
this.dataSource = new MatTableDataSource([]);
this.paginator = {} as MatPaginator;
}
defaultImage:string='assets/images/icons/no-photo.png';
ngOnInit(): void {
// this.pageSizeOptions = this._common.getPageSizeOptions();
// this.displayedColumns = this.getDisplayedColumns();
}
ngOnChanges(changes:SimpleChanges){
this.isLoading = true;
if (changes?.['tabelData'] && changes?.['tabelData'].currentValue) {
this.dataSource = new MatTableDataSource(this.tabelData);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
this.isLoading = false;
}
}Thanks

Amit MohantyRank #112 · 20K reputationPosted Jul 2, 2024, 1:36 AM EDT
Check the below example.
dynamic-mat-table.component.html:
dynamic-mat-table.component.ts:
import { Component, Input, OnChanges, SimpleChanges, ViewChild, ChangeDetectorRef, AfterViewInit, OnInit } from '@angular/core'; import { MatTableDataSource } from '@angular/material/table'; import { MatPaginator } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; @Component({ selector: 'app-dynamic-mat-table', templateUrl: './dynamic-mat-table.component.html', styleUrls: ['./dynamic-mat-table.component.css'] }) export class DynamicMatTableComponent implements OnInit, AfterViewInit, OnChanges { @Input() title?: string; @Input() tabelData: any = []; @Input() columnArray: string[] = []; @Input() columns: any = []; @Input() actionColumn: any = []; @Input() permission: any; dataSource: MatTableDataSource; @ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild(MatSort) sort: MatSort; isLoading: boolean = true; defaultImage: string = 'assets/images/icons/no-photo.png'; constructor(private cdr: ChangeDetectorRef) { this.dataSource = new MatTableDataSource([]); } ngOnInit(): void { // Initial setup if needed } ngOnChanges(changes: SimpleChanges): void { if (changes?.['tabelData'] && changes?.['tabelData'].currentValue) { this.updateTableData(changes['tabelData'].currentValue); } } ngAfterViewInit(): void { this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; } private updateTableData(data: any): void { this.dataSource.data = data; this.isLoading = false; this.cdr.detectChanges(); // Ensure Angular checks for changes } }