Create a one-of-a-kind Angular 6 material table component featuring unique custom columns

My goal is to streamline the process of creating custom material tables by using a specialized table component that allows me to quickly generate unique tables for different data sources with built-in pagination and sorting. All I need to provide are the displayedColumns and data. Utilizing the examples showcased here, I created this implementation (https://stackblitz.com/edit/angular-kp2ryv), but encountering an error in StackBlitz related to the usage of the custom column component.

ERROR TypeError: Cannot set property 'name' of undefined

This error message suggests that

@ViewChild(MatColumnDef) columnDef: MatColumnDef;
is unable to read the matColumnDef in the template for unknown reasons.

Here's how a table can be created using the custom component:

<dyn-table [data]="users" [displayedColumns]="displayedColumns">
    <dyn-col name="user_id"></dyn-col>
    <dyn-col name="user_name"></dyn-col>
</dyn-table>

This approach simplifies the following code:

<table mat-table #table [dataSource]="dataSource" class="table table-striped mat-elevation-z8">

    <ng-container matColumnDef="user_id">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> User id </th>
        <td mat-cell *matCellDef="let data">{{ data.user_id }}</td>
    </ng-container>

    <ng-container matColumnDef="user_name">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> User name </th>
        <td mat-cell *matCellDef="let data">{{ data.user_name }}</td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator #paginator [pageSize]="10"></mat-paginator>

I have spent significant time researching and troubleshooting, but unable to pinpoint the cause of this issue.

You can also view a functional version of the same StackBlitz without custom column components https://stackblitz.com/edit/angular-jw9whh

Answer №1

The reason behind this issue is due to the fact that you initially declared NgModule with material directives from the @angular/material module, but now you are attempting to access a directive from the @angular/material/table module.

Here's a quick test:

import {MatColumnDef} from '@angular/material/table';
import {MatColumnDef as RooColumnDef } from '@angular/material';

console.log(MatColumnDef, RooColumnDef, MatColumnDef === RooColumnDef);
                                                      ||
                                                     false

Therefore, it is essential to import both MatTableModule and MatColumnDef from the same module.

Access Forked 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

Issue: Kindly update your dependencies to the latest version of core-js@3

When trying to execute npm start, I encountered an error stating "An unhandled exception occurred: Could not find module "@angular-devkit/build-angular". I attempted to resolve this by installing it using npm install @angular-devkit/build-angular, but the ...

Best practice for filling an array using a promise

I am completely new to the world of modern JavaScript. My goal is to fill an array with data that I receive from a promise in a helperService. export class PeopleTableComponent implements OnInit { people: Array < Person > = []; constructor( ...

"NgComponentOutlet" is missing from the list of providers

In my Angular 11 project, I'm using @angular/material, @ngx-translate, and a library called icell-data-table. After successfully running the example project from the GitHub page on my local setup, I tried to replicate it on a Stackblitz demo and enco ...

Angular 11 component encountering issues with accessing server-side data

Recently, I encountered an issue when trying to connect the PHP API with the Angular service to retrieve data from the database. I am uncertain whether the problem lies within the service, the component.ts file, or the HTML section. Therefore, I have share ...

Tips for executing Firebase transactions involving read operations subsequent to write operations

Is there a method to incorporate read operations following write operations in nodejs for cloud and background functions? According to the information provided in the documentation, only server client libraries allow transactions with read operations afte ...

Defined interface with specific number of members

I am tasked with creating an interface that has only two members, one of which is optional and both have undefined names. Something like: interface MyInterface { [required: string]: string|number [optional: string]?: string|number } Unfortunately, ...

What is the best way to pass a cookie across multiple subdomains?

I am currently facing an issue with my setup where my express backend is hosted on , and the front-end is hosted on . The problem arises after logging in the frontend, as the auth server sets a cookie with "example.com" as the domain attribute, but the bro ...

By default, Angular 6 now imports RxJS 6 operators seamlessly into its files

My Angular application extensively uses various RxJS 6 operators like filter, take, and takeUntil in almost all files. Importing these operators explicitly in every file is quite cumbersome. I wish there was a way to make them globally accessible. Imagine ...

What is the best way to implement ES2023 functionalities in TypeScript?

I'm facing an issue while trying to utilize the ES2023 toReversed() method in TypeScript within my Next.js project. When building, I encounter the following error: Type error: Property 'toReversed' does not exist on type 'Job[]'. ...

Issue with Angular 8 - Material Table displaying incorrect data after deletion操作

I'm working on a material table that showcases different options through selects. My main object is the ngModel, which holds all the available options. These options are fetched from a database. Let's say I have a root item called menu, which m ...

Managing empty functions as properties of an object in a React, Redux, and Typescript environment

I'm feeling a little uncertain about how to properly test my file when using an object with a function that returns void. Below are the details. type Pros={ studentid: StudentId pageId?: PageID closeForm: () => void } When it comes to creating ...

Having trouble accessing an injector service within the promise of a dynamically loaded JavaScript function that has been assigned to a global variable

Query I am facing an issue while trying to integrate PayPal with Angular. I am encountering difficulties when attempting to call an injected service inside a function of the promise returned. Any assistance in resolving this would be greatly appreciated. ...

Precisely outline the function type that operates on an object, makes changes to its values, and then outputs the object in TypeScript

Can anyone help me create a function that generates a new object with the same keys as the input object, but with all values set to null? Here's the existing code: function nullify(arg) { var returnObj = {} for (var key in arg) { returnObj[ ...

Guide to Generating a Compilation Error with Method Decorators in Typescript

Currently, I am developing a library named expresskit which allows the use of decorators to define routes, params, and other functionalities for express. While refactoring the codebase, I am considering implementing restrictions on the types of responses a ...

The ngClass directive does not seem to be functioning properly when utilizing multiple conditions

Trying to apply [ngClass] under different conditions. Here is what I have: condition [ngClass]="{'validator':lang.VideoURL!=null, 'labeltitle': lang.VideoURL==null}" However, when the value of lang.VideoURL is null, the labeltitle cl ...

Issues with expected identifiers and type mismatch errors encountered when defining a TypeScript class

As someone who is still relatively new to coding, I am facing a challenge while trying to create a TypeScript class within an Angular project that is based on a complex JSON file. The issue arises from the way the properties were defined in the JSON using ...

Error: PrimeNG Treenode Component is having difficulty rendering the data

I'm currently working on a project in Angular 5 where I need to display data in a Treenode format. The data is coming from a service and is structured as follows (in object form): { "data": [ { "label": "Documents", ...

Check out the selected values in Ionic 3

I am trying to retrieve all the checked values from a checkbox list in an Ionic3 app when clicked. Below is the code snippet: <ion-content padding> <ion-list> <ion-item *ngFor="let item of items; let i= index"> <ion-label>{{i ...

AsyncPipe encounters an InvalidPipeArgument, signaling a pipe error

I've been exploring Async Pipe and seem to be stuck at this particular point... import { Component, OnDestroy } from '@angular/core'; import { AngularFireDatabase } from 'angularfire2/database'; @Component({ selector: 'a ...

Is there anyone out there who has integrated Leaflet and DataTables within the same user interface experience?

I'm currently facing a challenge with an application running in a sandbox environment where I am unable to create projects. Despite my efforts over the past few weeks, I can't seem to figure out how to get the DataTable to automatically select r ...