Search code examples
angularangular-material2angular-material-5

Set MatPaginator and MatSort in MatTableDataSource after getting data using ajax call


Sorting and pagination is not working after getting the value from backend using Ajax.

I am using following version:

Angular: 5.2.7 Material: 5.2.4 TypeScript: 2.5.3

My Code snippet:

<div class="form-created-by-me-header">
        <mat-form-field>
            <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
        </mat-form-field>
    </div>

    <div class="form-created-by-me-container mat-elevation-z8">

        <mat-table [dataSource]="dataSource" matSort>

            <!-- ID Column -->
            <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>

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

            <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
            <mat-row *matRowDef="let row; columns: displayedColumns;">
            </mat-row>
        </mat-table>

        <mat-paginator [pageSizeOptions]="[1, 5, 10, 25, 100]"></mat-paginator>

    export class FormCreatedByMeComponent {

      cratedFormsByMe: Array<SurveyForm>;
      dataSource: MatTableDataSource<SurveyForm> = new MatTableDataSource();


      public displayedColumns = ['id', 'name', 'description', 'questionCount', 'sharedWith', 'createdBy', 'createdDate', 'editBtn', 'deleteBtn'];

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

      constructor(private formService: SurveyFormService) {
        this.getCreatedFormsByMe();
      }

      private getCreatedFormsByMe(): void {
        this.formService.getCreatedFormsByMe().subscribe(
          cratedFormsByMe => {
            this.cratedFormsByMe = cratedFormsByMe;
            this.dataSource = new MatTableDataSource(this.cratedFormsByMe);
            this.dataSource.paginator = this.paginator;
            this.dataSource.sort = this.sort;
          });
      }


      applyFilter(filterValue: string) {
        filterValue = filterValue.trim(); // Remove whitespace
        filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
        this.dataSource.filter = filterValue;
      }

    }

In the above case nothing is happening. Please correct me if I am missing anything.


Solution

  • I solved this issue by adding a timeout around the paginator and sorter :

    setTimeout(() => {
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
    });