Error message when using Angular material table: Unable to access properties of undefined (specifically 'headerCell')

Having an issue with the header checkbox while working with Angular using material-table.

Whenever I try to add a 4th column for the checkbox, I encounter a strange error message:

 ERROR TypeError: Cannot read properties of undefined (reading 'headerCell')

Below is my TypeScript file:

export class VarViewNBtsComponent implements OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  columnsToDisplay: string[] = ['varSelect', 'varName', 'varType', 'varValue']; // Showing 4 columns
  ddsVariablesLeft = new MatTableDataSource<DDSVariable>(); // DDSVariable has only three entries
  selection = new SelectionModel<DDSVariable>(true, []);

  constructor(private sharedService: SharedService) {}
  ngOnInit() {
    this.ddsVariablesLeft.paginator = this.paginator;

    this.sharedService.getPathArrObs().subscribe((update) => {
      this.updTableData(update.data);
    });
  }
}

Here is the HTML template:

<div class="left-table">
    <table mat-table [dataSource]="ddsVariablesLeft">
        <tr mat-header-row *matHeaderRowDef="columnsToDisplay; sticky:true"></tr>
        <tr mat-row *matRowDef="let row; columns: columnsToDisplay" (click)="selection.toggle(row)"></tr>

        <ng-container matColumnDef="varSelect">
            <th mat-header-cell *matHeaderCellDef>
                <mat-checkbox (change)="$event ? masterToggle() : null"
                    [checked]="selection.hasValue() && isAllSelected()"
                    [indeterminate]="selection.hasValue() && !isAllSelected()">
                </mat-checkbox>
            </th>
            <td mat-cell *matCellDef="let row">
                <mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? selection.toggle(row) : null"
                    [checked]="selection.isSelected(row)">
                </mat-checkbox>
            </td>
        </ng-container>

        <!-- define column and its cells -->
        <ng-container matColumnDef="varName">
            <th mat-header-cell *matHeaderCellDef> Name </th>
            <td mat-cell *matCellDef="let ddsVariable"> {{ddsVariable.name}} </td>
        </ng-container>
        <!-- define column and its cells -->
        <ng-container matColumnDef="varType">
            <th mat-header-cell *matHeaderCellDef> Type </th>
            <td mat-cell *matCellDef="let ddsVariable"> {{ddsVariable.type}} </td>
        </ng-container>
        <!-- define column and its cells -->
        <ng-container matColumnDef="varValue">
            <th mat-header-cell *matHeaderCellDef> Value </th>
            <td mat-cell *matCellDef="let ddsVariable"> {{ddsVariable.value}} </td>
        </ng-container>

        <!-- <tr mat-row *matRowDef="let row; columns: columnsToDisplay"></tr> -->

    </table>
    <mat-paginator [pageSizeOptions]=" [5, 10, 20]" showFirstLastButtons></mat-paginator>
</div>

Furthermore, when I click on the header, the following errors occur: https://i.sstatic.net/QP0jt.png

Answer №1

It dawned on me on a bright afternoon that my html template contained not one, but two tables. The second table was attempting to display an array using the same columns, but internally it only had three columns to work with.

Silly mistake indeed! 😅

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

Setting up the TypeScript compiler locally in the package.json file

UPDATE #1: It appears that I have managed to come up with a functional configuration, but I am open to any suggestions for improvement. Feel free to check out the answer here: THE ORIGINAL INQUIRY: I am in the process of setting up my environment so that ...

Connect individual qualities of a diverse object (including embedded objects) to an array of linked lists

I'm currently working on a project where I need to dynamically derive a table column structure from any type of generic object. This object may contain properties of various types, and each property that is not an object itself should be considered a ...

Test Failure: Attempt to access 'componentInstance' property on a non-existent value

I am facing an issue where my unit tests are working fine with the angular2-seed project, but not with my own project that closely resembles angular2-seed. The only difference between my project and angular2-seed is that I use a gulpfile.ts without the to ...

Sorting an array of objects in TypeScript may result in a type error

My data includes various categories, ages, and countries... const data = [ { category: 'Fish', age: 10, country: 'United Kingdom' }, { category: 'Fish', age: 9, country: 'United Kingdom' }, { category: ...

How come my ts-mockito spy isn't delegating method calls properly?

In my code, I have a class named MyPresenter which has a method called doOperation(). This method calls another method on a View class that implements an interface and is passed in as a parameter. Below you can find the implementation of the class, interfa ...

Having trouble with Next.js 13 GitHub OAuth integration - it keeps redirecting me to Discord instead of signing me in

There's a perplexing issue troubling my application... The implementation of OAuth 2 with GitHub, Discord, and Google is causing some trouble. While Google and Discord authentication works smoothly, attempting to sign in via GitHub redirects me to Di ...

What is the best way to generate a random item when a button is clicked?

I'm currently working on a feature in my component that generates a random item each time I access the designated page. While the functionality is set to automatically refresh and showcase a new random item, I am now looking to trigger this action man ...

How to Dynamically Load SVGs in Angular 10 Without Using IMG or OBJECT Elements

I have been exploring a more streamlined method for loading SVG files without relying on IMG or OBJECT tags, as it limits my ability to control fill colors through external CSS. While using inline SVG seems like the best option, managing numerous component ...

Turn off Typescript compilation in Visual Studio for a webpage

My Angular website (not a computer science project) is integrated into a solution, causing Visual Studio 2019 to generate multiple TypeScript compilation errors while working on other projects within the same solution. You can see examples of these errors ...

How to display a div in Angular when hovering with ElementRef and Query List

I am having trouble implementing a ngFor loop in my project where I want to display a div on mouse hover using the @Input notation. This is how my HTML code looks: <div class="col s12 m6" style="position: relative" *ngFor="let res of hostInfo.resident ...

Error in typing on a prismic application utilizing a ContentRelationshipField

I am facing a type error in my Prismic Next.js application that I am struggling to resolve. While the app functions properly, I keep encountering type errors like the following: The property 'data' does not exist on the type 'ContentRelati ...

The resurgence of React JS in its role as a powerful tool

Although I struggle with React JS, I couldn't find a solution for this particular issue. I'm trying to incorporate this function into my tsx file and display it on the screen within a component. function displayUsers() { const UserListComponent ...

Stop the flow of data in the RxJS stream depending on a specific value within the stream

I developed a straightforward component featuring a single button that initiates and halts a sequence of numbers generated by RxJS timer. import { Component, OnInit } from '@angular/core'; import { BehaviorSubject, Observable, timer, merge } fro ...

What is the correct placement for the "require("firebase/firestore");" code in my Angular 4 project?

After doing thorough research on the internet and carefully reading through the Firestore documentation, I am facing difficulties in converting my partially built Angular (4) project. Following the instructions in the "Get Started with Cloud Firestore" gu ...

Can a TypeScript function be structured to return never (or throw) if a generic type extends a subtype without requiring casting?

(This code snippet is purely for demonstration purposes, as no real use-case exists here) I am attempting to create a function that throws an error if the input string is equal to "fish". I have achieved this using the as keyword, but I am curious if ther ...

Encountered an error while trying to load config.ts file because of an issue

Trying to set up a new protractor project to conduct tests on an angular site. Node.js, typescript, protractor, and jasmine are all installed globally. After running webdriver-manager update and webdriver-manager start in the project folder, I proceed to b ...

Function modifies global variable

What could be causing the global variable to change when using the function write_ACK_ONLY()? I'm passing the array rxUartBuffer to write_ACK_ONLY() as data = new Array(20), but upon checking the Log Output, it seems that the function is also modifyin ...

The checkbox component is currently not displaying on the ngx-datatable

The following HTML code snippet demonstrates a sample layout. The operations are functioning correctly, however, the checkbox is not visible. <ngx-datatable style="width: 90%" class="material" [rows]="rows" ...

Exploring the functionality of ngTemplateOutlet, the implementation of @ContentChild, and the benefits of using ng

Lately, I've been dedicating more time to grasp the concepts presented in the blog post titled Creating Reusable Components with NgTemplateOutlet in Angular If you want to see the code in action, it's available on stackblitz. Within the UsageEx ...

Issue with Angular Material Auto Complete not selecting items when filtered

Encountered a problem with the mat-autocomplete control in Angular Material where it fails to include the CSS class "mdc-list-item--selected" on the mat-option and also does not add the mat-pseudo-checkbox to a selected option when the contents are display ...