Mat table is failing to display the data stored in a TypeScript file within an array of objects

I am currently working on an Angular Material project to enhance my skills in Angular Material.

One challenge I am facing is trying to retrieve data from local storage, which was previously saved in a form, and display it using mat-table. However, the rendering process is not functioning correctly.

The specific error message that I encounter is:

ERROR Error: "Could not find column with id "name"."
Even though I have included the attribute for the name column in the object, this issue persists and I am puzzled by its occurrence.

export interface Rec {
    name: string;
    cert: string;
    cgpa: number;
}
const record: Rec[] = [] ;

// @title Dialog Overview

@Component({
    selector: 'app-modal',
    templateUrl: 'modal.component.html',
    styleUrls: ['modal.component.scss'],
})
export class ModalComponent implements OnInit {
    constructor(public dialog: MatDialog) {}
    recs: Rec[] = [];
    test() {
        record.length = 0;
        if (localStorage.reg) {
            const reg = JSON.parse(localStorage.getItem('reg'));
            // Retrieving data from two arrays into one array from localStorage
            for (let index = 0; index < reg.length; index++) {
                const pat = JSON.parse(localStorage.getItem(reg[index]));
                const patQ = JSON.parse(localStorage.getItem(reg[index] + 'Q'));
                const data = {
                    name: pat.sal + ' ' + pat.fname + ' ' + pat.lname,
                    cert: patQ.cert1,
                    cgpa: patQ.cgpa1,
                };
                record.push(data);
            }
            this.recs = record;
        }
        console.log(record);
    }

    ngOnInit() {
        this.test();
        console.log(this.recs);
    }

    openDialog() {
        const dialogRef = this.dialog.open(Modal);
    }
}
<!-- modal.component.html -->
<table mat-table #table [dataSource]="recs">
    <ng-container cdkColumnDef="name">
        <th mat-header-cell *cdkHeaderCellDef> Name </th>
        <td mat-cell *cdkCellDef="let row"> {{row.name}} </td>
    </ng-container>
    <ng-container cdkColumnDef="cert">
        <th mat-header-cell *cdkHeaderCellDef> Certification </th>
        <td mat-cell *cdkCellDef="let row"> {{row.cert}} </td>
    </ng-container>
    <ng-container cdkColumnDef="cgpa">
        <th mat-header-cell *cdkHeaderCellDef> C/GPA </th>
        <td mat-cell *cdkCellDef="let row"> {{row.cgpa}} </td>
    </ng-container>
    <tr mat-header-row *matHeaderRowDef="['name', 'cert', 'cgpa']"></tr>
    <tr mat-row *matRowDef="let row; columns: ['name', 'cert', 'cgpa'];"></tr>
</table>

Answer №1

After spending a couple of hours on it, I was able to come up with my own solution.

I successfully fixed the issue by replacing every instance of 'cdk' with 'mat' in the HTML file. This adjustment resulted in the table being displayed perfectly. *matHeaderCellDef should be used instead of *cdkHeaderCellDef

Answer №2

I don't see any issue with naming the column attributes in this code snippet. However, you can try making the following changes and let me know if the error still persists.

import { MatDialog, MatTableDataSource } from '@angular/material';

const records: any = [];

export class CustomModalComponent implements OnInit {
    constructor(public dialog: MatDialog) {}
    dataRecords: any;
    testMethod() {
        records.length = 0;
        if (localStorage.getItem('reg')) {
            ...
            this.dataRecords = new MatTableDataSource<RecordModel>(records);
        }
    }
}

Answer №3

Here is a suggested approach:

let localStorageData = localStorage.getItem('data'); // Retrieve data from local storage
if (localStorageData) { // Check if data exists in local storage, then parse and assign to MatTableDataSource
  let parsedData = JSON.parse(localStorageData);
  this.records = new MatTableDataSource(parsedData);
}
else { // If no data in local storage, set it first and then use it
  localStorage.setItem('data', JSON.stringify(ELEMENT_DATA));
  let parsedData = JSON.parse(localStorage.getItem('data'));
  this.records = new MatTableDataSource(parsedData);
}

Check out the StackBlitz demo here

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 battle of ng-bullet and karma-parallel: optimizing Angular unit test performance with test module configuration in before all block

I'm currently exploring different options to enhance the speed of my unit tests in an Angular project. After reading several blogs, I came across some suggestions: (1) ng-bullet (2) karma-paralle (3) ng test --browsers ChromeHeadless (4) configu ...

directive for a custom loader in ag-grid

I have incorporated ag-grid-angular into my project more than 20 times across different pages. Each time, I use a custom loader before the data is loaded. However, I would like to make this custom loader a directive so that it can be easily reused in all i ...

Having trouble initializing JwtHelper in an Angular2 project?

Encountering an unusual exception while attempting to create a new JwtHelper in Angular2. This error has been puzzling me for quite some time because of its cryptic nature. The problem arises when I try to include JwtHelper, causing an unexpected number er ...

Angular CLI customizes style path to load global styles lazily during the production build

Is there a method in angular-cli to generate multiple stylesheets using specific settings like this: .... "styles": [ "../styles/app.scss", { "input": "../styles/print.scss", "lazy": true, "output": "print" }, ], .... As a result, it will create prin ...

A guide on resolving the issue with node module live-server by switching from using require('opn') to require('open')

While attempting to deploy to my AWS environment, I encountered an error in the nodejs.log. /var/app/current/node_modules/opn/index.js:11 const wslToWindowsPath = async path => { ^^^^ SyntaxError: Unexpected identifier ...

Continue iterating using (forEach, map,...) until the object (children) has no more elements

I need to disable the active status for all elements within my object structure. Here is an example of my object: const obj = { name: 'obj1' , ative: true , children: [ { name: 'obj2' , ative: true , children: ...

The content of the string within the .ts file sourced from an external JSON document

I'm feeling a bit disoriented about this topic. Is it feasible to insert a string from an external JSON file into the .ts file? I aim to display the URLs of each item in an IONIC InAppBrowser. For this reason, I intend to generate a variable with a sp ...

Next.js is perplexing me by throwing an error about Event handlers not being able to be passed to Client Component props, even though the component clearly has "use client" at

My bundler generates a basic React component like this "use client"; "use strict";var a=Object.create;var r=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var i=Object.getOwnPropertyNames;var l=Object.getPrototypeOf,s=Objec ...

Is it possible to concurrently hot module reload both the server (.NET Core) and client (Angular)?

Using the command 'dotnet watch run' to monitor changes in server code and 'ng build --watch' for Angular code updates has been successful. It rebuilds the code correctly into directories "bin/" and "wwwroot/" respectively. myapp.cspro ...

Validating React components with TypeScript using an array structure where the field name serves as the key

Trying to implement form validation with React. I have a main Controller that contains the model and manages the validation process. The model is passed down to child controllers along with the validation errors. I am looking for a way to create an array ...

Choosing the value in a dropdown menu depending on the property value of an object using the select and angular methods

When editing a product with a category, I want to display the current category in a dropdown. The user should be able to change the category if desired, but upon loading the page, I want to show the selected value of the current product. Below is the HTML ...

Best method for including a property to a bespoke Angular 2 component

Our Angular 2 application features a custom input component. How can we properly incorporate an attribute into our custom component? Here is an outline of how our input component looks: input-debounce.component.ts var template = ` <input [type]= ...

Error encountered during Typescript compilation: The attribute 'raw' is not found within the context of the entity 'e' in express

In many instances, I have noticed that people use express.raw() or express.raw({type: 'application/json'}) as middleware in their requests... but is .raw() a legitimate method in Express? I am currently working with TypeScript and using Express ...

The deployment of the Heroku Angular app was unsuccessful as it encountered an error when trying to load a resource: the server returned a 404 (Not Found

Despite reading numerous answers on StackOverflow, I am still grappling with a problem. The application is deployed, but upon opening it, I am met with a white blank screen and error messages. It seems like the JavaScript files are returning an HTML file, ...

Receive only fresh data points

My Angular application utilizes the ngxs library as the store. I have a method that retrieves the last edited id: return this.store.select((state: AppStateModel) => state.lastEditedId) .pipe(filter(id => id > 0)); This method is used for d ...

process.nextTick: Unable to access undefined properties (reading 'indexOf')

After initiating npm start in my Angular project, an error is triggered: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80e4e5ecadf0f2efeac0b0aeb0aeb0">[email protected]</a> build > ng build Node.js vers ...

SCSS code for creating lists and maps

I am currently attempting to execute the code below in Angular v16. @use "sass:map"; @use "sass:list"; list.append(10px 20px, 30px); // ERROR expectedscss(css-lcurlyexpected) @debug list.append(10px 20px, 30px); $font-weights: (" ...

The expandable column headers in Primeng are mysteriously missing

I'm facing an issue with my expandable row in Angular2 using Primeng2, where the column headers for the expandable columns are not displaying. Below is the code snippet of my table with expandable rows: <p-dataTable [value]="activetrucks" expanda ...

I'm curious if there is an eslint rule specifically designed to identify and flag any unnecessary spaces between a block comment and the function or

Can anyone help me find a solution to prevent the following issue: /** * This is a comment */ function foo() { ... } I need it to be corrected and formatted like this: /** * This is a comment */ function foo() { ... } ...

Issues may arise when attempting to navigate within a lazy module using Angular Nativescript

Recently, I utilized a template called Nativescript-Tabs-Template from this GitHub repository. While attempting to navigate to a sibling component (both within the same lazy module), I encountered the following issue: showItem() { this.routerExtensi ...