4

[STACKBLITS LINK] I'm attempting a minimal angular material data table with sorting.

I've added the MatSortModule, implemented @ViewChild in the class, added the directives, set the dataSource.sort property etc. and I get the arrow on the table when I mouse hover, but the data does not sort.

Thoughts?

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { MatTableDataSource, MatSort } from "@angular/material";

    class Todo {
      id: string;
      description: string;
      complete: boolean;
    }
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      @ViewChild(MatSort, {static: false}) sort: MatSort;

      /**
      * Control column ordering and which columns are displayed.
      */
      displayedColumns:string[] =  ['id'];
      dataSource: MatTableDataSource<Todo>;

      ngOnInit() {
        const todos: Todo[] = [
          { id: '123', description: 'Complete me!', complete: false },
          { id: '321', description: 'You Completed me!', complete: true }];
        this.dataSource = new MatTableDataSource(todos);
        this.dataSource.sort = this.sort;
      }
    }


    <mat-table class="mat-elevation-z8" [dataSource]="dataSource" matSort>
      <ng-container matColumnDef="id">
        <mat-header-cell *matHeaderCellDef mat-sort-header>ID</mat-header-cell>
        <mat-cell *matCellDef="let row;">{{row.id}}</mat-cell>
      </ng-container>
      <mat-header-row *matHeaderRowDef="displayedColumns">
      </mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
    </mat-table>

2 Answers 2

4

The ViewChild for MatSort is undefined at ngOnInit since the view has not yet been initialized. To resolve this, set the MatSort on your dataSource after the view has initialized by using the ngAfterViewInit lifecycle hook.

ngAfterViewInit() {
    this.dataSource.sort = this.sort;
}
Sign up to request clarification or add additional context in comments.

Comments

1

I had the same issue, you need to set the MatSort. This is how I fixed it

@ViewChild(MatSort, {static: false}) set  sortMeeting (ms: MatSort){
this._sort = ms;
this.renewDataSource(); }

............................................

ngOnInit(){
this.dataSource = new MatTableDataSource(todos);
this.renewDataSource();
}


renewDataSource() {
this.dataSource.sort = this._sort;
}

I hope it helps. :)

1 Comment

We have to wait until AfterViewInit in order to make sure that the sortDirective has been fully initialized.

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.