简体   繁体   中英

Angular Material 12: Customize Table Sort Button

I have an Angular Material Table with sorting:

table.component.html :

<table mat-table [dataSource]="dataSource" matSort>

  <th mat-header-cell mat-sort-header *matHeaderCellDef>
    <span>Name</span>
  </th>

  ...
</table>

This displays a sort button in the header cell in the usual Material style.

I need to change the style (not the functionality) of the sort button. How can I do that? I tried creating my own button, but I do not know how to access the Material sort button's functionality.

table.component.html :

<table mat-table [dataSource]="dataSource" matSort>

  <th mat-header-cell *matHeaderCellDef>
    <span>Name</span>

    <!-- `style` contains some custom styling -->
    <!-- `(click)` should do the same as on the Material sort button -->
    <button mat-button mat-icon-button (click)=??? style=...>
      <mat-icon>sort</mat-icon>
    </button>
  </th>

  ...
</table>

I don't know if is the best aproach, but you can

1.-makes display none the "arrows". For this, in your styles.css -the style that is common to all the aplication- you can write

.mat-sort-header-ste,.mat-sort-header-arrow {
  display:none!important
}

2.- then, if your sort is called sort , you need play with the values of "sort.active" and sort.direction`

a HARD code, for a column called "name" can be

@ViewChild(MatSort) sort: MatSort;
this.dataSource.sort = this.sort;

<th mat-header-cell *matHeaderCellDef mat-sort-header> 
{{sort && sort.active=="name"?
      sort.direction=='asc'?'Up':
      sort.direction=='desc'?'Down':
      null:null
}} Name </th>

You can use [ngClass] or another aproach

NOTE: if you write al the bottom of your component

<pre>
{{sort?.active|json}} {{sort?.direction|json}}
</pre>

You can see how the values change

an ugly stackblitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM