0

I have an Angular mat-table that won't sort case-insensitively. I've tried many different ways and nothing works. Here's my latest attempt:

template:

<table mat-table [dataSource]="dataSource" matSort matSortActive="customer" matSortDirection="asc">

  <ng-container matColumnDef="customer">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>Customer Name</th>
    <td mat-cell *matCellDef="let element">{{element.customer}}</a> </td>
  </ng-container>...

component

export class Customer {
  customerid: number;
  name: string;
  phone: string;
}

export class CustomerComponent implements OnInit {
  @ViewChild(MatSort) sort: MatSort;
  dataSource = new MatTableDataSource<Customer>([]);

  ngOnInit() {
    this.dataSource.sortingDataAccessor = (data, sortHeaderId) => data[sortHeaderId].toLocaleLowerCase();
  }
    
  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }

The dataSource gets populated from a database query. The table sorts fine but all the uppercase customers appear first, followed by the lower case ones.

Suggestions?

user3217883
  • 1,216
  • 4
  • 38
  • 65

2 Answers2

0

Simplest solution is:

    export class Customer {
      customerid: number;
      name: string;
      phone: string;
    
      get lowerName(){
        return this.name?.toLowerCase()
      }
   }

And in template

<ng-container matColumnDef="lowerName">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>Customer Name</th>
    <td mat-cell *matCellDef="let element">{{element.customer}}</a> </td>
  </ng-container>
0

matColumnDef must fit the property in your view model

<ng-container matColumnDef="name">