2

I'm trying to use angular material data table with angular 6 but I don't get sorting headers to show up. I don't get any errors and nothing is showing up at all.

<mat-card>
<mat-card-content>
  <div class="example-container mat-elevation-z8">
    <mat-table #table [dataSource]="dataSource" matSort>

      <!-- Position Column -->
      <ng-container matColumnDef="StartDate">
        <mat-header-cell *matHeaderCellDef mat-sort-header> Datum </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.StartDate}} </mat-cell>
      </ng-container>

      <ng-container matColumnDef="StartTime">
        <mat-header-cell *matHeaderCellDef mat-sort-header> Uhrzeit </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.StartTime}} </mat-cell>
      </ng-container>

      <ng-container matColumnDef="customer.CustomerShort">
        <mat-header-cell *matHeaderCellDef> Kunde </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.customer.CustomerShort}} </mat-cell>
      </ng-container>

test-drive-list-component.html

I have imported MatSort module and linked MatSort.

export class TestDriveListComponent implements OnInit {
  displayedColumns = ['StartDate', 'StartTime', 'customer.CustomerShort', 
  'user.UserShort',
  'automobile.AutomobileShort', 'automobile.licenseNumber', 'status', 
  'actions'];

  testdrives: TestDrive[];

  dataSource: TestdriveDataSource | null;

  query = '';


  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(private dataService: DataService, public dialog: MatDialog) { }

  ngOnInit() {
    this.dataSource = new TestdriveDataSource(this.dataService, this.sort);
  }

  applyFilter() {
    this.dataSource.filter = this.query;
  }

I am not very experienced with angular and any help would be appreciated.

1 Answer 1

2
Dear @Florian Glaesser,    
Please try below steps once:
    1. try to  import MatSortModule in your app.module.ts
    2. Next we need to define matsort local variable as below:

          @ViewChild(MatSort) matSort: MatSort;
          private sort: any;
          @ViewChild(MatSort) set content(content: ElementRef) {
        this.sort = content;
        if (this.sort) {
          this.dataSource.sort = this.sort;
        }
    3. once you got your data in the ngOnit, bind the matSort as below:
     ngOnInit() {
        this.dataSource = new MatTableDataSource(<your service which returns the data>);
        this.dataSource.sort = this.matSort;
      }
This worked for me. Please try it once.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.