How can I get column header width (angular mat-table) in typescript? I tried to use id and get elementById.clientWidth but it doesn't work for mat table column.
I need to get the size of each column from the table to set the filter width above it for each column.
import { CommonModule } from '@angular/common';
import { Component, ViewChild } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatPaginator, MatPaginatorModule } from '@angular/material/paginator';
import { MatSort, MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { MatInputModule } from '@angular/material/input';
export interface PeriodicElement {
name: string;
position: number;
weight: number;
symbol: string;
}
const ELEMENT_DATA: PeriodicElement[] = [
{ position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
{ position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
{ position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
{ position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
{ position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
{ position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
{ position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N' },
{ position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O' },
{ position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F' },
{ position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne' },
];
/**
* @title Basic use of `<table mat-table>`
*/
@Component({
selector: 'table-basic-example',
styleUrl: 'table-basic-example.css',
templateUrl: 'table-basic-example.html',
standalone: true,
imports: [
MatFormFieldModule,
MatTableModule,
MatSortModule,
MatPaginatorModule,
MatFormFieldModule,
FormsModule,
ReactiveFormsModule,
CommonModule,
MatFormFieldModule,
MatInputModule,
],
})
export class TableBasicExample {
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
dataSource = ELEMENT_DATA;
ngModel: any = {};
filteredColumn: string;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
getWidthForColumn(column: string): string {
if (document.getElementById(column) != null) {
let ss = document.getElementById(column)!.clientWidth;
console.log(ss);
}
return 'background-color: white';
}
applyFilter(event: Event, value?: any, columnName?: any) {}
}
<mat-form-field
[style]="getWidthForColumn(column)"
*ngFor="let column of displayedColumns; index as i"
appearance="outline"
>
<mat-label>{{column}}</mat-label>
<input
matInput
[(ngModel)]="ngModel[column]"
(keyup)="applyFilter($event, ngModel[column], column)"
#input
/>
</mat-form-field>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<!--- Note that these columns can be defined in any order.
The actual rendered columns are set as a property on the row definition" -->
<!-- Position Column -->
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef>No.</th>
<td mat-cell *matCellDef="let element">{{element.position}}</td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name">
<th id="test" mat-header-cell *matHeaderCellDef>Name</th>
<td mat-cell *matCellDef="let element">{{element.name}}</td>
</ng-container>
<!-- Weight Column -->
<ng-container matColumnDef="weight">
<th mat-header-cell *matHeaderCellDef>Weight</th>
<td mat-cell *matCellDef="let element">{{element.weight}}</td>
</ng-container>
<!-- Symbol Column -->
<ng-container matColumnDef="symbol">
<th mat-header-cell *matHeaderCellDef>Symbol</th>
<td mat-cell *matCellDef="let element">{{element.symbol}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
You can take the ViewChildren
of all the headers (MatHeaderCell
directive), then access the HTML element using (read: ElementRef
). Which we then use to access the widths. I create an empty array, then load the widths in the ngAfterViewInit
hook. Then I use ngStyle
to add the widths using the index of the loop.
import { CommonModule } from '@angular/common';
import {
Component,
ElementRef,
QueryList,
ViewChild,
ViewChildren,
} from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatPaginator, MatPaginatorModule } from '@angular/material/paginator';
import { MatSort, MatSortModule } from '@angular/material/sort';
import { MatTableModule, MatHeaderCell } from '@angular/material/table';
import { MatInputModule } from '@angular/material/input';
export interface PeriodicElement {
name: string;
position: number;
weight: number;
symbol: string;
}
const ELEMENT_DATA: PeriodicElement[] = [
{ position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
{ position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
{ position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
{ position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
{ position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
{ position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
{ position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N' },
{ position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O' },
{ position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F' },
{ position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne' },
];
/**
* @title Basic use of `<table mat-table>`
*/
@Component({
selector: 'table-basic-example',
styleUrl: 'table-basic-example.css',
templateUrl: 'table-basic-example.html',
standalone: true,
imports: [
MatFormFieldModule,
MatTableModule,
MatSortModule,
MatPaginatorModule,
MatFormFieldModule,
FormsModule,
ReactiveFormsModule,
CommonModule,
MatFormFieldModule,
MatInputModule,
],
})
export class TableBasicExample {
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
dataSource = ELEMENT_DATA;
ngModel: any = {};
filteredColumn: string;
widths = new Array(this.displayedColumns.length);
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
@ViewChildren(MatHeaderCell, { read: ElementRef })
headers: QueryList<ElementRef<any>>;
getWidthForColumn(column: string): string {
// console.log(column);
// let ss = document.getElementById('test');
// console.log(ss);
return 'background-color: white';
}
ngAfterViewInit() {
console.log(
this.headers.map((header: ElementRef<any>, index: number) => {
const width =
header?.nativeElement?.getBoundingClientRect()?.width || 0;
this.widths[index] = width;
})
);
}
applyFilter(event: Event, value?: any, columnName?: any) {}
}
<mat-form-field
[ngStyle]="{'width.px': widths[i]}"
*ngFor="let column of displayedColumns; index as i"
appearance="outline"
>
<mat-label>{{column}}</mat-label>
<input
matInput
[(ngModel)]="ngModel[column]"
(keyup)="applyFilter($event, ngModel[column], column)"
placeholder=""
#input
/>
</mat-form-field>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<!--- Note that these columns can be defined in any order.
The actual rendered columns are set as a property on the row definition" -->
<!-- Position Column -->
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef>No.</th>
<td mat-cell *matCellDef="let element">{{element.position}}</td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name">
<th id="test" mat-header-cell *matHeaderCellDef>Name</th>
<td mat-cell *matCellDef="let element">{{element.name}}</td>
</ng-container>
<!-- Weight Column -->
<ng-container matColumnDef="weight">
<th mat-header-cell *matHeaderCellDef>Weight</th>
<td mat-cell *matCellDef="let element">{{element.weight}}</td>
</ng-container>
<!-- Symbol Column -->
<ng-container matColumnDef="symbol">
<th mat-header-cell *matHeaderCellDef>Symbol</th>
<td mat-cell *matCellDef="let element">{{element.symbol}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>