Data not displaying in material table

I am currently testing out the Angular Material table component, but I'm facing an issue where it's not displaying any data and showing the error:

Could not find column with id "id".

This is confusing to me because my data does have a row with the column id.

The in-memory data service provider code snippet is as follows:

import { Injectable } from '@angular/core';
import { InMemoryDbService, RequestInfo } from 'angular-in-memory-web-api'
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class Contact {
  id!: string;
  name!: string;
  email!: string;

}

export class BackendService implements InMemoryDbService {

  constructor() { }
  createDb(reqInfo?: RequestInfo | undefined): {} | Observable<{}> | Promise<{}> {
    let contacts = [
      { id: 1, name: 'Contact 1', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385b57564c595b4c09785d55595154165b5755">[email protected]</a>' },
      { id: 2, name: 'Contact 2', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aac9c5c4decbc9de98eacfc7cbc3c684c9c5c7">[email protected]</a>' },
      { id: 3, name: 'Contact 3', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="284b47465c494b5c1b684d45494144064b4745">[email protected]</a>' },
      { id: 4, name: 'Contact 4', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="34575b5a4055574000745159555d581a575b59">[email protected]</a>' }
    ];

    return { contacts };
  }
}

The component code section looks like this:

import { Component, OnInit, ViewChild } from '@angular/core';
import { ContactService } from '../contact.service';
import { firstValueFrom } from 'rxjs';
import { Contact } from '../backend.service';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';

const COLUMNS_SCHEMA = [
  {
    key: "id",
    type: "text",
    label: "Id"
  },
  {
    key: "name",
    type: "text",
    label: "Name"
  },
  {
    key: "email",
    type: "text",
    label: "E-mail"
  },
]
@Component({
  selector: 'app-contact-list',
  templateUrl: './contact-list.component.html',
  styleUrl: './contact-list.component.css'
})
export class ContactListComponent implements OnInit {
  @ViewChild('paginator') paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  dataSource!: MatTableDataSource<Contact>;
  displayedColumns: string[] = COLUMNS_SCHEMA.map((col) => col.key);
  columnsSchema: any = COLUMNS_SCHEMA;

  contacts: any[] = [];
  constructor(private contactService: ContactService) {

  }
  async ngOnInit(): Promise<void> {

    const data: any = await firstValueFrom(this.contactService.getContacts());
    console.log(data);
    this.contacts = data;

    this.dataSource = new MatTableDataSource(this.contacts);
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
    console.log(this.displayedColumns);
  }
}

Finally, here is how my template is structured:

<mat-table class="lessons-table mat-elevation-z8" [dataSource]="dataSource">
  <ng-container matColumnDef="date">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Id </mat-header-cell>
    <mat-cell *matCellDef="let contact">
      <input type="text" matInput [value]="contact.id" readonly>
    </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>

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

</mat-table>

Answer №1

The error message indicates that the <mat-table> is missing a column definition for "id". It is essential to define all columns as listed in the displayColumns array. Alternatively, you can remove any unnecessary elements from the displayColumns array.

For more information, check out Column Template Definitions.

<mat-table class="lessons-table mat-elevation-z8" [dataSource]="dataSource">
  <ng-container matColumnDef="id">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Id </mat-header-cell>
    <mat-cell *matCellDef="let contact">
      <input type="text" matInput [value]="contact.id" readonly />
      {{ contact.id }}
    </mat-cell>
  </ng-container>

  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
    <mat-cell *matCellDef="let contact">
      <input type="text" matInput [value]="contact.name" readonly />
      {{ contact.name }}
    </mat-cell>
  </ng-container>

  <ng-container matColumnDef="email">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Email </mat-header-cell>
    <mat-cell *matCellDef="let contact">
      <input type="text" matInput [value]="contact.email" readonly />
      {{ contact.email }}
    </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>

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

Check out the Demo on StackBlitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure that a particular key type is determined by the value of another key within the object (Utilizing Discriminated Unions)

The title of my question may not have been clear about what I am looking for, but what I need is something known as discriminated unions. You can find more information about it here: https://www.typescriptlang.org/docs/handbook/unions-and-intersections.htm ...

What is the best way to transfer props between components using typescript?

I have a unique button component that I need to include in another component. The button type and interface I am using are as follows: type IButton = { className?: string, onClick?: MouseEventHandler; children: React.ReactNode; props: IButt ...

Model Mongoose TypeScript Interface Type

I am working with 2 models in my project import {model, Schema, Types} from 'mongoose' interface IResource { user : Types.ObjectId | IUsers, type : Types.ObjectId | IResourceData, value : number, lastUpdate : number | Date, ...

The Angular Reactive Forms error message indicates that attempting to assign a 'string' type to an 'AbstractControl' parameter is invalid

While attempting to add a string value to a formArray using material forms, I encountered the following error message: 'Argument of type 'string' is not assignable to parameter of type 'AbstractControl'.' If I try adding a ...

Setting up Datatables for Pagination Features

Looking for advice on setting up datatables with paginated results. For example: Here is an example of paginated results from my backend API: { "total": 50, "per_page": 15, "current_page": 1, "last_page": 4, "next_page_url": "http://domain.app ...

Changing the base URL in an Angular HTTPclient GET request for custom endpoint

When attempting to send a GET request to a specific URL, I'm encountering an issue where the original URL is being replaced by a different one, leading to a request being made to a non-existent URL. Below is the code snippet: import { HttpClient } f ...

Is it possible for Angular's IVY Compiler to inject classes from external packages?

Our team specializes in building numerous universal packages that are free from Angular dependencies. We use our own @injectable decorator to decorate the classes in these packages, and TypeScript emits metadata for types. "experimentalDecorators": true ...

Utilize Angular 2 routes within your express application

I've recently developed a web application that has the server-side built on Node.js and the client-side on Angular. The file structure of the project is as follows: |_ api |_ client |_ config |_ models |_ package.json |_ server.js However, I'm ...

What is the best way to provide inputs to a personalized validation function?

I am seeking a solution to pass an array of prefix strings to my custom validator in order to validate that the value begins with one of the specified prefixes. Below is the code snippet for my current validator: @ValidatorConstraint({ name: 'prefixVa ...

Transforming Ajax POST requests into Angular 8 API calls

After receiving the Ajax Post call from the client, I was able to successfully insert static data when opening the PHP API file in a browser. Now, I am attempting to utilize Angular to achieve the same result. However, I am struggling to understand how to ...

What is the process for importing components from a Stencil library into a React application?

After successfully creating: a stencilJS component library named "my-lib" using the "npm init stencil" wizard and an Ionic React app using "ionic start myApp tabs" I am now trying to incorporate the default "my-component," aka MyComponent from my-lib. H ...

Typescript threw an error stating "Cannot access properties of an undefined object" in the React-Redux-axios

As a backend developer, I am not very familiar with frontend development. However, for my solo project, I am attempting to create some frontend functionalities including user login right after setting the password. Below is the code snippet from UserSlice. ...

Encountering an issue on Safari: WeakMap variable not found in .NET Core 1.1.0 and Angular 2 application

I recently deployed a .NET Core 1.1.0 + Angular 2 + Typescript app on ASPHostPortal and encountered an issue while accessing it from Safari. The console showed the following exception: Can't find variable:WeakMap This caused the site to not load p ...

Is it possible for me to test events in protractorjs/cucumberjs?

Using Cucumber.js Instead of Java I have an Angular component that incorporates a directive to adjust focus once a certain number of characters are entered into the input field. I want to verify this behavior in my Cucumber tests. 1) Is the webElement.se ...

Entering a series of predetermined value types into an array

I am currently trying to determine the best way to define a type for a specific value in TypeScript. The value in question looks like this: [{"source": "bar"}, 1483228800, 1484265600] Initially, I came up with the following approach: interface FieldSour ...

Exploring the concept of recursive method calls in TypeScript

I am trying to call the filterArr method inside the filterArr itself. Here is my current implementation: function filterArr(array, search) { var result = []; array.forEach((a)=> { var temp = [], o = {}, ...

openapi-generator is generating subpar api documentation for TypeScript

Executing the command below to generate an auto-generated API using openapi-generator (v6.0.1 - stable): openapi-generator-cli generate -i app.json -g typescript -o src/main/api The json file is valid. Validation was done using openapi-generator-cli valid ...

Implementing service injection within filters in NestJS

Looking to integrate nestjs-config into the custom exception handler below: import { ExceptionFilter, Catch, ArgumentsHost, Injectable } from '@nestjs/common'; import { HttpException } from '@nestjs/common'; import { InjectConfig } fro ...

Transmitting a cookie across domains using an HTTP get request in Angular 2

Is there a way to send a cookie with Angular 2 across domains? const headers = new Headers({ 'Cookie': 'test=me'}); let options = new RequestOptions({ headers }); return this.http.get(this.specialUrl, options ) .map( (res: ...

Unable to bring in CSS module in a .tsx file

I am currently working on a basic React application with TypeScript, but I am encountering difficulty when trying to import a CSS file into my index.tsx file. I have successfully imported the index.css file using this method: import './index.css&apo ...