The Angular Material table is failing to display any data and is throwing an error stating that _columnCssClassName is not

I have a challenge with my Angular Material application. I am attempting to display a list of customers received from an API call. The app compiles successfully, but I keep encountering this error in the browser console:

ERROR Error: Uncaught (in promise): TypeError: columnDef._columnCssClassName is not iterable (cannot read property undefined) TypeError: columnDef._columnCssClassName is not iterable (cannot read property undefined)

What could be causing this issue? I suspect it might relate to how I am populating the data in the table columns.

To tackle this problem, I created a 'Customers' interface structured as follows:

export interface Customers {
  _links: {
    first: {
      href: string;
    };
    last: {
      href: string;
    };
    next: {
      href: string;
    }
    self: {
      href: string;
    };
  };
  _embedded: {
    customers: [
      {
        id: string;
        internal_id: string;
        name: string;
        name2: string;
        address: string;
        address_post_nr: string;
        phone: string;
        email: string;
        gdpr: string,
        mailing: string,
        tags: string;
      }
    ]
  };
  page: number;
  page_count: number;
  page_size: number;
  total_items: number;
}

Furthermore, I have developed a component where I aim to present my customers in a table showcasing these columns: Id, name, address, email, mailing, gdpr, tags.

Below is the code snippet from the component.ts file:

export class CustomersComponent implements OnInit, OnDestroy{

  displayedColumns: string [] = ['Id', 'name', 'address', 'email', 'mailing', 'gdpr', 'tags'];
  public dataSource: MatTableDataSource<Customers["_embedded"]>;

  private customerSubscription: Subscription;

  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  @ViewChild(MatSort, { static: true }) sort: MatSort;

  private dataArray: any;
  constructor(
    private customersServcice: CustomersService,
  )
  { }

  ngOnInit() {
    this.getAllCustomers();
  }

  getAllCustomers() {
    this.customerSubscription = this.customersServcice.getAllCustomersList().subscribe(
      (res) => {
        console.log('res: ', res);
        this.dataArray = res;
        this.dataSource = new MatTableDataSource<Customers["_embedded"]>(this.dataArray);
        console.log('this.dataSource: ', this.dataSource);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      });
  }

  ngOnDestroy() {
    if(this.customerSubscription) {
      this.customerSubscription.unsubscribe();
    }
  }
}

Also, here's the HTML table code for the components:

  <table mat-table [dataSource]="dataSource" class="crm-table mat-elevation-z0">
    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef> Id </th>
      <td mat-cell *matCellDef="let element" class="left-text"> {{element.id}} </td>
    </ng-container>
    ...
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let element; columns: displayedColumns;"></tr>
  </table>

Answer №1

It appears that the issue lies with the type specified for the MatTableDataSource.

public dataSource: MatTableDataSource<Customers["_embedded"]>

After examining the <mat-table> element provided, it seems that the correct type should be:

Customers["_embedded"]["customers"][0]
.

  1. Adjust the type for MatTableDataSource.
public dataSource: MatTableDataSource<Customers["_embedded"]["customers"][0]>;
  1. Update the type for MatTableDataSource in the Subscription as well. Confirm that the dataArray is an array of type
    Customers["_embedded"]["customers"][0]
    .
this.dataSource = new MatTableDataSource<Customers["_embedded"]["customers"][0]>(this.dataArray);
  1. Additionally, ensure that the Id is written in lowercase within the displayedColumns.
displayedColumns: string[] = ['id', 'name', 'address', 'email', 'mailing', 'gdpr', 'tags'];

Alternatively, I recommend creating a new interface called CustomerItem.

export interface CustomerItem {
  id: string;
  internal_id: string;
  name: string;
  name2: string;
  address: string;
  address_post_nr: string;
  phone: string;
  email: string;
  gdpr: string,
  mailing: string,
  tags: string;
}

export interface Customers {
  _links: {
    first: {
      href: string;
    };
    last: {
      href: string;
    };
    next: {
      href: string;
    }
    self: {
      href: string;
    };
  };
  _embedded: {
    customers: CustomerItem[]
  };
  page: number;
  page_count: number;
  page_size: number;
  total_items: number;
}

Then, update the dataSource type to:

public dataSource: MatTableDataSource<CustomerItem>;

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

The issue I'm facing is that the style loader is failing to load the CSS within the <head

I am currently facing an issue with importing my CSS into my webpack bundle for our Angular 1 application. Initially, everything was working fine as we bundled our application using Webpack. The HTML included the bundle and vendor scripts, additional Java ...

A function similar to setCell for modifying form fields in JqGrid

After searching through numerous answers from @Oleg, I couldn't find the solution I was looking for. I am dealing with a grid where I can edit inline in certain fields. Specifically, I am working with autocomplete functionality and when I select an it ...

Steps to improve the appearance of the Header on a dataTable during Dragging

I am working on creating a table that can be reordered using mat-table and MatTableDataSource. However, I would like the column to have a white background color instead of being transparent when dragged. Is there a way to achieve this? <table mat-tab ...

Creating custom components that encapsulate the functionality of Angular Material tabs component

I am aiming to incorporate the Angular Material tabs component within my shared components. Here is the component I'm attempting to wrap: Note: Each tab can display a component: <mat-tab-group> <mat-tab label="First"> Content ...

Arrangement of pipe operators in RXJS Angular 5

Do you think my operators are in the correct order? The code snippet below shows that the console logs from the two taps display the same values. Something seems off, right? return this.pcs.getAvailableMaterials(currentProduct.id).pipe( map( ...

Steps for integrating Laravel pagination into a Bootstrap table with the wenzhixin plugin

I am facing an issue where the laravel pagination() function returns data in a format that is not understood by bootstrap table. How can I resolve this problem? Route: Route::post('/student-statement', [StatementController::class, 'index&ap ...

JavaScript Sort function malfunctioning and not correctly sorting

I am having trouble sorting div elements by price values. The code seems to be working fine, but the sorting of numbers doesn't appear to be completely accurate. For example, in my jsfiddle, when the button is clicked, the number 21.35 is displayed a ...

Choose a select few checkboxes and then disable the remaining checkboxes using Vue and Laravel

I'm currently working on a project using Laravel 10 and Vue3. In the form, users are allowed to select only 3 checkboxes. Once they have selected 3 checkboxes, all remaining checkboxes should be disabled. I attempted to implement this functionality a ...

I keep encountering the issue where I receive the message "Unable to access property 'innerText' of an undefined element" when running the Array forEach function. This problem seems to be happening within the HTMLInputElement section of the code

I am facing an issue where the error occurs because "cardTxt" is not recognized as a string. I verified this using typeof syntax, but I'm unable to understand why it can't be a string. This code snippet includes the use of bootstrap for styling. ...

sorting in React table not functioning properly for computed column

I have a column titled 'EV/Resource ($ per oz)' that appears to not sort correctly in my react table. Instead of sorting in ascending or descending order, it randomizes the table sort. I'm unsure if I am handling this as a "calculated column ...

Is it possible to determine if a variable is unset using isset?

Currently, I am utilizing the following code snippet to verify if isset is not set. For instance: if(!isset($_REQUEST['search'])) { } else if(!isset($_REQUEST['submit'])) {} I would like clarification on whether !isset is considered ...

Angular | Dynamic | Flexible | ResetConfiguration

Seeking Input What method is preferable for adjusting routes in Angular applications: utilizing routes.resetConfig(newRouteArray) or reloading the application on resize and dynamically creating routeArrays based on screen width? I welcome alternative sol ...

What is the best way to pause the function execution until the ajax call is finished?

I have the following code snippet: function validate(){ if (document.getElementById('<%=txtSeqNo.ClientId %>').value.trim() == "") { alert('Please enter Sequence number.'); return false; } var result = checkduplicateseq( ...

Loop through JSON results in Ionic using Angular

I am struggling to retrieve data from a JSON file in Object format using Typescript. When I try to fetch the data from the API, it doesn't display as expected. Typescript this.http.get('http://example.com/api') .subscribe((data) => { ...

Global Day "Sequence" Initiates Subtraction Instead of Preserving Its Authentic Structure

While using Python's Selenium, I am facing a challenge when trying to "inject" an international date string in the specified format into a web page. Unfortunately, instead of getting the expected string, I am getting a result that seems like subtracti ...

What causes the $injector:modulerr error when trying to integrate angular-carousel?

After integrating angular-carousel into my application, I encountered the following error: Failed to instantiate module ngMaterial due to: Error: [$injector:modulerr] http://errors.angularjs.org/1.5.8/$injector/modulerr?p0=n...) at Error (native) ...

retrieving attribute values from JSON objects using JavaScript

I am struggling to extract certain attribute values from a JSON output and use them as input for a function in JavaScript. I need assistance with this task! Below is the JSON data that I want to work with, specifically aiming to extract the filename valu ...

Attaching and detaching dynamic views in Angular within an ngFor loop

I'm currently dealing with an issue where I have a list of chat items that are loaded dynamically. When a user clicks on a specific item, I need to open/close a static component/section (such as a reactions menu) right below that particular chat item. ...

Issue: TypeError - 'process.env' can only accept a configurable while installing windows-build-tools

Unable to successfully download installers. Encountered an error: TypeError: 'process.env' can only accept a configurable, writable, and enumerable data descriptor. I attempted to resolve this issue by running the command npm install --global wi ...

Displaying country-specific API details (such as capital and currency) in a card container when selecting a country from a dropdown menu

My objective is to display the card information for South Africa as the default value, even before entering any country's name into the search bar input field or selecting a specific country from the provided list. I am utilizing the restcountries API ...