What potential issue could result in a property length of null error while working with a Material Data Table?

I'm experiencing a similar issue as the one discussed in this post, but none of the suggestions there have resolved my problem, and my scenario has some differences.

In my case, a parent component is assigning an array to a child component's input property, which is then used to create a data source for a mat table. Here is a snippet of my code:

parent.component.html:

<mat-tab label="Accounts">
  <app-accounts [accounts]="accountOwner?.accounts"></app-accounts>
</mat-tab>

child.component.ts:

@Component({ /// })
  export class AppAccountComponent implements OnInit, OnChanges {
  @Input() accounts: MyAccount[];
tableColumns: string[] = ['name', 'number', 'startDate', 'endDate'];
accountDataSource: MatTableDataSource<MyAccount>;

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

constructor() {
  // Tried the recommended approach from the linked thread, to no avail:
  // this.accountDataSource = new MatTableDataSource<MyAccount>();
}

ngOnInit(): void {
  this.sort.active = 'name';
  this.sort.direction = 'asc';
}

ngOnChanges(changes: SimpleChanges): void {
  this.accountDataSource = new MatTableDataSource<MyAccount>(this.accounts);
  this.accountDataSource.sort = this.sort;
  this.accountDataSource.paginator = this.paginator;
}
}

child.component.html:

<table mat-table [dataSource]="accountsDataSource" class="mat-elevation-z1" matSort>
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
    <td mat-cell *matCellDef="let account"> {{account.name}} </td>
  </ng-container>

  <ng-container matColumnDef="number">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Number </th>
    <td mat-cell *matCellDef="let account"> {{account.number}} </td>
  </ng-container>

  <ng-container matColumnDef="startDate">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Effective Date </th>
    <td mat-cell *matCellDef="let account"> {{account.startDate | date:'mediumDate'}} </td>
  </ng-container>

  <ng-container matColumnDef="endDate">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Expiration Date </th>
    <td mat-cell *matCellDef="let account"> {{account.endDate | date:'mediumDate'}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="tableColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: tableColumns;"></tr>
</table>
<mat-paginator [pageSizeOptions]="[5, 10, 20]" [disabled]="!accountsDataSource" [pageSize]="5" showFirstLastButtons>
</mat-paginator>

The structure of the MyAccounts interface is as follows:

export interface MyAccount {
  number: string;
  name: string;
  startDate: Date;
  endDate?: Date;
}

The data is being displayed correctly, however, I am encountering a "property length of null" exception in the console window, which seems to be originating from MatTableDataSource._filterData().

Answer №1

After some investigation, I managed to unravel this mystery and feel slightly sheepish about the solution.

It turns out that during the initial invocation of ngOnChanges, the array was null but on subsequent invocations it had a value. To resolve this issue, I made the following adjustment:

this.accountDataSource = new MatTableDataSource<MyAccount>(this.accounts ? this.accounts : []);

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

Guide to organizing the table according to the values (timestamps) in a specific column

In one of the tables I'm working with, there is a column called uploadedOn. You can see it in action here: https://stackblitz.com/edit/angular-ivy-tntvst?devToolsHeight=33&file=src/app/app.component.ts 1: https://i.stack.imgur.com/aQ6wh.png. My g ...

Retrieve the attributes associated with a feature layer to display in a Pop-up Template using ArcGIS Javascript

Is there a way to retrieve all attributes (fields) from a feature layer for a PopupTemplate without explicitly listing them in the fieldInfos object when coding in Angular? .ts const template = { title: "{NAME} in {COUNTY}", cont ...

What is the best way to shorten text in Angular 2?

Can the length of a string be limited to a specific number of characters in AngularJS code? For example, if I need to restrict the title length to 20 characters {{ data.title }}. Is there a built-in pipe or filter available to set this character limit? ...

typescript defining callback parameter type based on callback arguments

function funcOneCustom<T extends boolean = false>(isTrue: T) { type RETURN = T extends true ? string : number; return (isTrue ? "Nice" : 20) as RETURN; } function funcCbCustom<T>(cb: (isTrue: boolean) => T) { const getFirst = () => ...

Guide on how to address the problem of the @tawk.to/tawk-messenger-react module's absence of TypeScript definitions

Is there a way to fix the issue of missing TypeScript definitions for the @tawk.to/tawk-messenger-react module? The module '@tawk.to/tawk-messenger-react' does not have a declaration file. 'c:/develop/eachblock/aquatrack/management-tool-app ...

Adding images in real-time

I am currently working on an Angular application where I need to assign unique images to each button. Here is the HTML code snippet: <div *ngFor="let item of myItems"> <button class="custom-button"><img src="../../assets/img/flower.png ...

Establishing a simulated testing environment with a JSON file in Angular 2

I am attempting to create a mock environment setup similar to the one described in this thread. environment.mock.ts export const environment = { production: false, PRODUCT_LIST : 'http://localhost:4200/app/mock-json/products.json', SAVE_C ...

How can I display an ng-container or ng-template without using *ngIf?

I am trying to incorporate the tappable directive into the ion-card component within a custom component. I am using an @Input() myInputBool, similar to this: <ng-container *ngIf="myInputBool"> <ion-card> <ng-container r ...

Tips for creating a stylish, blurred, and centered box for a login form on a full-size background that is also responsive

I attempted to create a login form on an HTML page using Angular, featuring a full-size background image that is centered. The form itself is contained within a div with a blurred background, also centered both horizontally and vertically within the browse ...

Display a loading screen while transitioning between routes in Angular 2

Is there a way to implement a loading screen for route changes in Angular 2? ...

Error in NextJS: The name 'NextApplicationPage' cannot be found

const { Component, pageProps}: { Component: NextApplicationPage; pageProps: any } = props After implementing the code above with 'Component' type set to NextApplicationPage, an error message pops up stating, The name 'NextApplicationPage&ap ...

What is the proper way to utilize RxJS to append a new property to every object within an array that is returned as an Observable?

I'm not very familiar with RxJS and I have a question. In an Angular service class, there is a method that retrieves data from Firebase Firestore database: async getAllEmployees() { return <Observable<User[]>> this.firestore.collectio ...

Is there a way to show text as symbols in Primeng components?

Check out this helpful example that demonstrates what I am attempting to achieve. I have implemented p-menu from primeng. Is there a method to convert text into symbols like &trade to ™ and &#8482 to ®? ...

Angular looping, split into multiple columns

I have a complex multi-checkbox form with up to 100 items in an array and a variable number of columns ranging from 1 to 5. For example, if I have 14 items and want to display them in 4 columns: []item 1 []item 5 []item 9 []item 13 []item 2 []item 6 ...

The useState variable remains unchanged even after being updated in useEffect due to the event

Currently, I am facing an issue in updating a stateful variable cameraPosition using TypeScript, React, and Babylon.js. Below is the code snippet: const camera = scene?.cameras[0]; const prevPositionRef = useRef<Nullable<Vector3>>(null); ...

Tips for testing an Angular Service that utilizes AngularFireDatabase by utilizing Jasmine Spy/Mock

I am currently testing my data service, and while I can successfully test it using real services like AngularFireDatabase, I am facing issues with getting the mocked version to work for testing purposes. The DataStorage class in use is designed to combine ...

How can you annotate and inherit a class method that returns an array of itself?

In the following example, I present a simplistic representation of code that may not align with standard HTML or front-end conventions. Please excuse any confusion this may cause. TL, DR I am facing challenges in specifying a return type for a method tha ...

Implementing pagination within an Angular 11 Mat-table with grouping feature

Encountering an interesting issue with MatTable pagination and grouping simultaneously. I have two components each with a Mat-table featuring Pagination+Grouping. ComponentOne functions smoothly without any issues. When choosing to display 5 elements pe ...

Adding a second interface to a Prop in Typescript React: a step-by-step guide

import { ReactNode, DetailedHTMLProps, FormHTMLAttributes } from "react"; import { FieldValues, SubmitHandler, useForm, UseFormReturn, } from "react-hook-form"; // I am looking to incorporate the DetailedHTMLProps<FormHTMLAt ...

Tips for accessing images in Angular 24 lazy loaded modules

I have a collection of images that need to be shared throughout my application. There are 2 lazy-loaded modules - Login and Overview. The image I require is located in src/assets/images/logo.png and needs to be accessible in both the Login and Overview com ...