Issue with Material Sort functionality when null objects are present

I've encountered an issue with my code. I created a feature that adds empty rows if there are less than 5 rows, but now the sort function is no longer functioning properly. Strangely, when I remove the for loop responsible for adding empty rows, the sorting starts working again. Is there any solution to resolve this problem?

        this.userData = data.info;
        //when i remove this if condition the sorting works
        if(this.userData.length <=5){
          for (let index = 0; index <= 6 - this.userData.length; index++) {
              this.userData.push(Object.create(null));
          }
        }
        this.dataSource = new MatTableDataSource(this.userData);
        this.dataSource.sort = this.sort;
        this.dataSource.paginator = this.paginator;

I'm currently stuck as I really need the table to include empty rows. Any assistance would be greatly appreciated.

Answer â„–1

To improve efficiency, consider replacing the if and for loop with a more streamlined while loop:

while(this.userData.length <= 5){
   this.userData.push(Object.create(null));
}

Prior to integrating the data into MatTableDataSource, it is advisable to arrange the data in the 'userData' Object according to the 'name' property. This sort function places null objects at the end of the list.

this.userData.sort((a,b) => (b.name) ? ((a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0)) : -1);

If you wish to allow users to customize the sorting, bind to the matSortChange event on your mat-table component.

<mat-table (matSortChange)="onSortChange($event)">

Every time this event is triggered, re-sort the data accordingly.

onSortChange(sort: MatSort): void {
   const data: Array<UserData> = this.dataSource.data.slice();
   if (!sort.active || sort.direction === '') {
      this.dataSource.data = data;
      return;
   }

   this.dataSource.data = data.sort((a, b) => {
      let isAsc: boolean = sort.direction === 'asc';
      let valSortProperty = sort.active;
      return b[valSortProperty] ? this.compare(a[valSortProperty], b[valSortProperty], isAsc) : -1;
   });

   this.dataSource = new MatTableDataSource<UserData>(this.dataSource.data);
   this.dataSource.paginator = this.paginator;
}

compare(a: any, b: any, isAsc: boolean): number {
   if(isAsc){
      return (a > b) ? 1 : ((b > a) ? -1 : 0)
   } else {
      return (a < b) ? 1 : ((b < a) ? -1 : 0)
   }
}

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

Utilize ngrx effects for making API requests without storing the response in the store

Currently, I am working on an Angular project that utilizes ngrx/store. One of my components requires data from the backend. The usual flow for this scenario is as follows: dispatch a Action trigger an Effect --> make a call to the backend update the ...

Error: Jest + Typescript does not recognize the "describe" function

When setting up Jest with ts-jest, I encountered the error "ReferenceError: describe is not defined" during runtime. Check out this minimal example for more information: https://github.com/PFight/jest-ts-describe-not-defined-problem I'm not sure what ...

Steps to resolve the issue: angular/[email protected] - unable to resolve the dependency

Encountering a challenging compiler error, I am determined to find a solution. Despite numerous attempts to install different library versions, the issue persists. It appears that the firebaseui-angular package necessitates an alternative angular/fire ver ...

Unable to install a specific commit of an angular library from GitHub using npm

While utilizing Angular 2.0.0-beta.15, I encountered the inability to upgrade it. Thus, I had to search for a specific commit from the ng2-dnd library on GitHub. Upon locating a compatible commit for version 2.0.0-beta.17: "ng2-dnd": "git://github.com/ak ...

Accessing the NestJS DI container directly allows for seamless integration of dependency

I have been using NestJS for the past 4 months after working with PHP for 5 years, mainly with Symfony. With PHP, I had the ability to access the compiled DI container and retrieve any necessary service from it. For example, in an application with service ...

Surprising Outcome when Dealing with Instance Type - Allowing extra properties that are not explicitly stated in the type

I've come across an issue with the InstanceType Utility Type. I am trying to create a function that takes a class constructor and an instance of that class. For instance: export type Class<T=any> = { new(...args: any[]): T; }; function acceptC ...

Encountering a "Cannot POST" error in Angular upon redirection to a callback URL with a SAML response

Currently, I'm implementing SAML authentication in my angular application that will be hosted on AWS. The angular code is stored in a separate project from the webapi where Itfoxtec saml library is being utilized. The flow of communication between my ...

"Encountering issues with getStaticPaths not generating any paths

I have a folder named data which contains a file called events.ts: export const EventsData: Event[] = [ { name: 'School-Uniform-Distribution', images: ['/community/conferences/react-foo.png', "/community/conferences/react ...

My NPM Install is throwing multiple errors (error number 1). What steps can be taken to troubleshoot and

I'm encountering an issue with my Angular project while trying to run npm install from the package.json file. Here are some details: Node version - 12.13.0 Angular CLI - 7.2.4 gyp ERR! configure error gyp ERR! stack Error: unable to verify the fi ...

Is there a way to disable a field or div in Angular 8 based on a user's role permission, rather than just showing or hiding it with ngx-per

<div *customPermissions="['USER']"> <div><input type="text" placeholder="testing custom permission"></input></div> </div> This code snippet displays a div based on custom p ...

Tips for typing a subset of an array containing string literals in TypeScript

Is it possible to have a function called createFields that takes a generic Object type, such as User, and extracts a subset of keys that can be inferred with a string literal array, similar to the selectable property in Fields? If so, how can this be ach ...

Storing references to the DOM elements external to the rendering component

Just diving into the world of Electron + Typescript, so please bear with me. Currently, I'm experimenting with what can be achieved within Electron. Issue: My goal is to manipulate DOM elements outside of the renderer. I pass a button as a parameter ...

JavaScript: specify parameters for function inputs

I'm curious about optimizing Javascript/Typescript functions arguments for clean code. To demonstrate, let's consider a basic example. Imagine I have a React component with a view property as props: <Grid view="Horizontal" /> ty ...

Opening and closing a default Bootstrap modal in Angular 2

Instead of using angular2-bootstrap or ng2-bs3-modal as recommended in the discussions on Angular 2 Bootstrap Modal and Angular 2.0 and Modal Dialog, I want to explore other options. I understand how the Bootstrap modal opens and closes: The display pro ...

Using React.PureComponent, the list component efficiently renders each item with optimized performance

We've developed a reusable list component in ReactJS. To address performance concerns, we decided to incorporate the shouldComponentUpdate method to dictate when our list component should re-render. public shouldComponentUpdate(nextProps: TreeItemInt ...

Error: Issue determining the type of variable. Unable to eliminate type 'any'

I am trying to load some widgets from a template object (possibly JSON in the future). Here's an example: type RectangleTemplate = { name: 'Rectangle'; props: { width: number; height: number; } }; type ButtonTemplate = { nam ...

Getting the most out of TypeScript Enum in Angular 6

I have a situation where I am storing the numeric value of an enum in my database and then displaying it in another part of the UI. Now, I need to retrieve the string value linked with that numeric value from the enum in a separate Angular component. Here ...

Encountering issues with Typescript when using absolute paths

After updating a forked repository, I noticed that TypeScript is no longer recognizing absolute paths. Surprisingly, I have not made any changes to my tsconfig.json: { "compilerOptions": { "allowJs": true, "allowSyntheticDefaultImports": true, ...

Incorporating Swift code into a NativeScript app

I'm attempting to integrate native Swift code into my NativeScript application. Despite following the guidelines provided in the documentation, specifically adding a Swift source file to App_Resources/iOS/src/ and using publicly exposed classes direct ...

Tips for fetching individual item information from Firebase real-time database using Angular 9 and displaying it in an HTML format

product.component.ts import { AngularFireDatabase } from '@angular/fire/database'; import { ProductService } from './../product.service'; import { ActivatedRoute } from '@angular/router'; import { Component, OnInit} from &apo ...