Search code examples
javascriptangulartypescriptcomponentsangular-material-table

Why my Angular mat-table is not showing up


I am using Angular 15.2 and having following data structure defined in the component.ts file:

export interface Employee {
  Id : number,  
  FirstName:string, 
  LastName:string,  
  Email:string,
  Gender:string,    
  JobTitle:string
}
...
_the_content : Employee[] =[{
    "Id": 1,
    "FirstName": "Johannah",
    "LastName": "Kiffin"
  }, {
    "Id": 2,
    "FirstName": "Eldin",
    "LastName": "Astbery"
  }, {
    "Id": 3,
    "FirstName": "Nahum",
    "LastName": "Mounce"
  }, {
    "Id": 4,
    "FirstName": "Gallard",
    "LastName": "Standell"
  }];

Then in component.html, I have:

<div class="container">
  <table class="table table-responsive table-striped center">
    <tr>
      <th>#Id</th>
      <th>First Name</th>
      <th>Last Name</th>
    </tr>
    <tr *ngFor="let row of _the_content">
      <td>{{row.Id}}</td>
      <td>{{row.FirstName}}</td>
      <td>{{row.LastName}}</td>
    </tr>
  </table>
<div>
<div class="container">
  <table mat-table class="emp-data-table" [dataSource]="_the_content">
  
    <ng-container matColumnDef="id">
        <th mat-header-cell *matHeaderCellDef>#Id</th>
        <td mat-cell class="id-cell" *matCellDef="let row">{{row.Id}}</td>
    </ng-container>
  
    <ng-container matColumnDef="first-name">
        <th mat-header-cell *matHeaderCellDef>First Name</th>
        <td mat-cell class="first-name-cell" *matCellDef="let row">{{row.FirstName}}</td>
    </ng-container>
  
    <ng-container matColumnDef="last-name">
        <th mat-header-cell *matHeaderCellDef>Last Name</th>
        <td mat-cell class="last-name-cell" *matCellDef="let row">{{row.LastName}}</td>
    </ng-container>
    
    <tr mat-header-row *matHeaderRowDef="_displayed_columns"></tr>
    
    <tr mat-row *matRowDef="let row; columns: _displayed_columns"></tr>
    
  </table>
<div>

Also in app.module.ts, I have:

import { MatInputModule } from "@angular/material/input";
import { MatTableModule } from "@angular/material/table";
import { MatSortModule } from "@angular/material/sort";
import { MatPaginatorModule } from "@angular/material/paginator";
import { MatProgressSpinnerModule } from "@angular/material/progress-spinner"

...
imports: [
    ...
    MatInputModule,
    MatTableModule,
    MatPaginatorModule,
    MatSortModule,
    MatProgressSpinnerModule
    ...
]

Now the first table is showing up, but the second table does not.

What am I missing here?

I made sure the data are available in the html file by creating two tables referencing them, and the first table is showing while the second is not.


Solution

  • Make sure your _displayed_columns is populated correctly. _displayed_columns: string[] = ['id', 'first-name', 'last-name'];