An arrow when click applies a sorting to it, it can either be a ascending sort or a descending sort - no such thing as sort being cancelled... No matter how many times we click on a column heading, some (asc or dsc) sorting will be applied and hence we should see the arrow with opacity: 1
. To do this, we keep track of each click and apply the boldArrow
class to th
. Styling for opacity:1
is done when in reference to this class
relevant TS:
@Component({
selector: 'table-sorting-example',
styleUrls: ['table-sorting-example.css'],
templateUrl: 'table-sorting-example.html',
})
export class TableSortingExample implements OnInit {
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
dataSource = new MatTableDataSource(ELEMENT_DATA);
sortedStatus: boolean[] = [];
@ViewChild(MatSort) sort: MatSort;
ngOnInit() {
this.sortedStatus = [false, false, false, false];
this.dataSource.sort = this.sort;
}
sortedStyler(columnNumber) {
console.log("sortedStyler with", columnNumber);
if (this.sortedStatus[columnNumber] == true) {
//this.sortedStatus[columnNumber] = false;
} else {
this.sortedStatus[columnNumber] = true;
for (var i = 0; i < this.sortedStatus.length; i++) {
if (i != columnNumber) { this.sortedStatus[i] = false; }
}
}
}
}
relevant HTML:
<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
<!-- Position Column -->
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef mat-sort-header (click)='sortedStyler(0)' [ngClass]="sortedStatus[0] === true ? 'boldArrow' : ''"> No. </th>
<td mat-cell *matCellDef="let element"> {{element.position}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header (click)='sortedStyler(1)' [ngClass]="sortedStatus[1] === true ? 'boldArrow' : ''"> Name </th>
<td mat-cell *matCellDef="let element"> {{element.name}} </td>
</ng-container>
<!-- Weight Column -->
<ng-container matColumnDef="weight">
<th mat-header-cell *matHeaderCellDef mat-sort-header (click)='sortedStyler(2)' [ngClass]="sortedStatus[2] === true ? 'boldArrow' : ''"> Weight </th>
<td mat-cell *matCellDef="let element"> {{element.weight}} </td>
</ng-container>
<!-- Symbol Column -->
<ng-container matColumnDef="symbol">
<th mat-header-cell *matHeaderCellDef mat-sort-header (click)='sortedStyler(3)' [ngClass]="sortedStatus[3] === true ? 'boldArrow' : ''"> 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>
relevant css:
::ng-deep .boldArrow .mat-sort-header-arrow.ng-trigger.ng-trigger-arrowPosition {
opacity: 1 !important;
}
working stackblitz here