Home > Net >  Angular material table sort not working when using http.get()
Angular material table sort not working when using http.get()

Time:12-04

In my attempts to use angular material tables to display data, I have found that when using hardcoded inline json, my table sorts as expected. However, when retrieving json via http.get(), the sort no longer works.

A sample service created to illustrate this question:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class ApiService {
  constructor(private http: HttpClient) {}

  getDataHttp(): Observable<any> {
    return this.http.get('assets/data.json');
  }

  getDataInline(): Observable<any> {
    var data = [
      . . .
    ];
    return of(data);
  }
}

and the respective table component:

import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { ApiService } from '../../services/api.service';

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css'],
})
export class TableComponent implements OnInit {
  @Input() name: string = '';
  displayedColumns = ['id', 'name', 'value'];
  dataSource: MatTableDataSource<any>;

  @ViewChild(MatSort) sort!: MatSort;

  constructor(private api: ApiService) {
    this.dataSource = new MatTableDataSource();
  }

  ngOnInit(): void {
    if (this.name === 'Inline') {
      this.api.getDataInline().subscribe((response) => {
        this.dataSource = new MatTableDataSource(response);
      });
    } else if (this.name === 'Http') {
      this.api.getDataHttp().subscribe((response) => {
        this.dataSource = new MatTableDataSource(response);
      });
    }
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }
}

and the corresponding view:

<div>
  <h5>{{ name }}</h5>
  <table mat-table [dataSource]="dataSource" matSort>
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>

    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Id</th>
      <td mat-cell *matCellDef="let row">{{ row.id }}</td>
    </ng-container>

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

    <ng-container matColumnDef="value">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Value</th>
      <td mat-cell *matCellDef="let row">{{ row.value }}</td>
    </ng-container>
  </table>
</div>

Stackblitz: https://stackblitz.com/edit/angular-ivy-qk3s2y

Why does sorting work for the inline table, but not for the http table?

CodePudding user response:

This:

ngAfterViewInit() {
  this.dataSource.sort = this.sort;
}

is executed before the http-request is done. We need to remember this is asynchronous, so you should set the sort after the data has been received:

  this.api.getDataHttp().subscribe((response) => {
    this.dataSource = new MatTableDataSource(response);
    this.dataSource.sort = this.sort; // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  });

STACKBLITZ

  • Related