Components: [MatTable], [MatSort] Sorting stops work if table has *ngIf attribute

Created on 30 Jan 2019  路  4Comments  路  Source: angular/components

What is the expected behavior?

Sorting should work correct.

What is the current behavior?

<table *ngIf='true' mat-table [dataSource]="dataSource" matSort>

*ngIf makes sorting not work.

What are the steps to reproduce?

https://stackblitz.com/edit/angular-sn7pfz?file=app/table-sorting-example.html

Which versions of Angular, Material, OS, TypeScript, browsers are affected?

Angular = 7.2.2
Material = 7.3.0
OS = ALL
TypeScript = ALL

Is there anything else we should know?

Most helpful comment

I fixed it by replacing
@ViewChild(MatSort,{static:true}) paginator: MatSort;
with :

 @ViewChild(MatSort, {static: false}) set content(sort: MatSort) {
    this.dataSource.sort = sort;
  }

and on my NgOnInit :

   this.userDataService.getUserData().subscribe(
      data => {
        this.dataSource = new MatTableDataSource<UserData>(data);
      },
      error => {
        console.log(error)
      }

    )

All 4 comments

The ViewChild for MatSort is undefined at ngOnInit since the view has not yet had a chance to evaluate if the table will be displayed. To resolve this, set the MatSort on your data source after view has initialized by using the ngAfterViewInit hook.

https://stackblitz.com/edit/angular-sn7pfz-c8f9xc?file=app/table-sorting-example.ts

I also have this issue when using *ngIf. Placing the code inside ngAfterViewInit couldn't really help to solve the problem.

I fixed it by replacing
@ViewChild(MatSort,{static:true}) paginator: MatSort;
with :

 @ViewChild(MatSort, {static: false}) set content(sort: MatSort) {
    this.dataSource.sort = sort;
  }

and on my NgOnInit :

   this.userDataService.getUserData().subscribe(
      data => {
        this.dataSource = new MatTableDataSource<UserData>(data);
      },
      error => {
        console.log(error)
      }

    )

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

_This action has been performed automatically by a bot._

Was this page helpful?
0 / 5 - 0 ratings

Related issues

LoganDupont picture LoganDupont  路  3Comments

savaryt picture savaryt  路  3Comments

jelbourn picture jelbourn  路  3Comments

vanor89 picture vanor89  路  3Comments

3mp3ri0r picture 3mp3ri0r  路  3Comments