1

I am implementing a table with mat-table. I want to bind the data source to an array whose data is fetched by an API. When I fetch the data using httpclient and subscribe to the result, the table doesn't render anything.

However, I used the "json" pipe to render the array outside the table, and it works.

Here is my code:

import { HttpClient } from '@angular/common/http';


constructor(private http: HttpClient) {}

displayedColumns: string[] = ['firstname', 'lastname'];
users: any[] = [];

ngOnInit(): void {
  this.http.get('/api/users').subscribe(
    (data) => {
      this.users = data
    },
    (error) => {
      console.log(error)
    }
  );
}

The HTML is as follows:

<table #table mat-table [dataSource]="users" class="mat-elevation-z8">
    <ng-container matColumnDef="firstname">
        <th mat-header-cell *matHeaderCellDef>First Name</th>
        <td mat-cell *matCellDef="let element"> {{element.firstname}} </td>
    </ng-container>
    <ng-container matColumnDef="lastname">
        <th mat-header-cell *matHeaderCellDef>Last Name</th>
        <td mat-cell *matCellDef="let element"> {{element.lastname}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
Ebrahim Mansour
  • 363
  • 1
  • 4
  • 13

1 Answers1

1

Since the table optimizes for performance, it will not automatically check for changes to the data array. Instead, when objects are added, removed, or moved on the data array, you can trigger an update to the table's rendered rows by calling its renderRows() method.

https://material.angular.io/components/table/overview

Calling renderRows() on Angular Material Table