title: Sort a list component in Angular
body: <p>I'm trying to sort my list-component that I've created with angular material. </p>
  
  <pre><code>&lt;div style="width:30%;"&gt;
          &lt;mat-nav-list matSort (matSortChange)="sortData($event)"&gt;
              &lt;th mat-sort-header="stuff.name"&gt;Name&lt;/th&gt;
              &lt;mat-list-item *ngFor="let stuff of vehicleDetails"&gt;
                  &lt;button matLine (click)="updateInfo(stuff.id)"&gt; {{ stuff.name }} &lt;/button&gt;
                  &lt;button mat-icon-button id="btn" *ngIf='check(stuff.alarm)' matTooltip="{{stuff.alarm[tooltipIndex(stuff)]?.timestamp}} - {{stuff.alarm[tooltipIndex(stuff)]?.description}}"&gt;
                      &lt;mat-icon&gt;info&lt;/mat-icon&gt;
                  &lt;/button&gt;
              &lt;/mat-list-item&gt;
          &lt;/mat-nav-list&gt;
      &lt;/div&gt;
  </code></pre>
  
  <p>The data displayed in the list is a bunch of vehicle names. It comes from my vehicleDetails which is an array of type VehicleDetail, containing properties such as name, id, etc. Right now I'm trying to sort by name. Im using the following functions when trying to achieve this functionality:</p>
  
  <pre><code> export class VehiclelistComponent implements OnInit, AfterViewChecked
   {
  
  vehicleDetails: VehicleDetail[] = [];
  sortedVehicleDetails: VehicleDetail[];
  
  sortData(sort: Sort) {
      const data = this.vehicleDetails.slice();
      if (!sort.active || sort.direction === '') {
        this.sortedVehicleDetails = data;
        return;
      }
      this.sortedVehicleDetails = data.sort((a, b) =&gt; {
        const isAsc = sort.direction === 'asc';
        switch (sort.active) {
          case 'name':
            return this.compare(a.name, b.name, isAsc);
          default:
            return 0;
        }
      });
    }
  
    compare(a, b, isAsc) {
      return (a &lt; b ? -1 : 1) * (isAsc ? 1 : -1);
    }
  </code></pre>
  
  <p>My ngOnInit and ngAfterViewChecked looks like this</p>
  
  <pre><code>ngOnInit() {
      // Init vehicles
      this.getVehicleDetails();
  
     }
  
    ngAfterViewChecked() {
      this.sortedVehicleDetails = this.vehicleDetails.slice();
    }
  </code></pre>
  
  <p>How can I solve my problem so I can sort by name or any other properties? </p>