I am working with a dynamic mat-table where columns are added and populated on the fly. The table headers are styled using divs and spans. My goal is to change the color of a header to black when clicked, but also un-toggle any previously selected header.
At the moment, I have managed to toggle a header's color, but I am struggling with untoggling another header. Initially, all the spans were being toggled at once, but I was able to fix this by toggling based on each span's ID.
Below is a snippet of the HTML code I have implemented:
<table mat-table [dataSource]="dataSource">
<ng-container matColumnDef="{{column.columnName1}}" *ngFor = "let column of displayColumns">
<th mat-header-cell *matHeaderCellDef>
<div *ngIf = "column.stackedHeader">
<div [ngStyle] = "{'color': (column.toggled) ? 'black' : 'grey'}" (click) = "toggleColumn($event)" class = "column-header" id = "{{column.columnName1}}">
{{ column.columnHeader1 }}
</div>
<div (click) = "toggleColumn($event)" class = "column-header" id = "{{column.columnName2}}">
{{ column.columnHeader2 }}
</div>
</div>
<div *ngIf = "!column.stackedHeader" (click) = "toggleLocationColumn($event)" class = "column-header" id = "{{column.columnName1}}">
{{column.columnHeader1}}
</div>
</th>
toggleColumn($event) {
const columnId = $event.toElement.id;
this.columnToggled.emit($event);
for (let i = 0; i <= this.displayColumns.length; i++) {
if (columnId === this.displayColumns[i].columnName1) {
this.displayColumns[i].toggled = !this.displayColumns[i].toggled;
}
}
}
Here is an example array that I use to populate the table:
[{
columnName1: 'Pickup',
columnHeader1: 'Pickup',
columnName2: 'Delivery',
columnHeader2: 'Delivery',
stackedHeader: true,
stackedRow: true,
toggled: false
},
{
columnName1: 'FromCity',
columnHeader1: 'From',
columnName2: 'ToCity',
columnHeader2: 'To',
stackedHeader: true,
stackedRow: true,
toggled: false
}]