Challenges with sorting and pagination in Angular 6's material-table

I am facing a challenge in my Angular6 material-data-table application where I need to display and manipulate a complex JSON structure received from a REST endpoint. While the data is successfully displayed, I am struggling to implement pagination and sorting features.

Despite trying various solutions found on Stack Overflow, I have been unsuccessful in resolving the issue. It's possible that the problem lies in how I am accessing the REST data (even though I can access it in the constructor) but I haven't been able to pinpoint the exact issue. No error messages are being displayed, and all imports appear to be correct.

file: employee-list.ts

import { MatSort } from '@angular/material/sort';
import { MatTableDataSource, MatPaginator } from '@angular/material';
import { Component, OnInit, ViewChild } from '@angular/core';
import { UserService } from '../../services/user.service';
import { Entry } from '../../interfaces/entry';


@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {

  typesafeEntries: Entry[];
  listData: MatTableDataSource<Entry>;
  displayedColumns: string[] = ['searched', 'german', 'dialectEntry', 'partOfSpeech', 'linguisticUsage', 'synonyms', 'actions'];

  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;


  constructor(private userService: UserService) {

    this.userService.getCompleteSearchResults("SomeLanguageData1", "SomeLanguageData2", "wordToLookFor")
      .subscribe((resp: Entry[]) => {;

        this.typesafeEntries = resp;
        this.listData = new MatTableDataSource<Entry>(this.typesafeEntries);
        this.listData.sort = this.sort;

      });
  }

  ngOnInit() {  }

}
[
    {
        "dialectA": {
            "dialectId": "5d1220343269a28de043eda9",
            "dialectEntry": "House",
            ...
...
// end of first entry
{...}, {...} ]

Expected result: when clicking on sort, the content of this column should be sorted. the same with pagination.

here a screenshot: screenshot from project

Answer №1

When attempting to sort this column, the issue arises because Angular Material is looking for data based on the column name dialectEntry. However, the actual data for this column is nested within another property called element.dialectB.dialectEntry. As a result, Angular Material cannot find the data it needs under element.dialectEntry, causing the sorting functionality to malfunction.

To resolve this issue, you will need to implement your own custom sortingDataAccessor and specify to Angular Material where to locate the data. Refer to the documentation available here for more information on the sortingDataAccessor.

In your specific scenario, the solution would involve creating the following code snippet:

this.listData.sortingDataAccessor = (item, property) => {
  if (property === 'dialectEntry') {
    return item.dialectB.dialectEntry;
  } else {
    return item[property];
  }
};

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

Utilizing CSS in Angular applications

I am currently working on an Angular 2 application and I am fairly new to Angular. I am facing an issue where my CSS does not seem to be applying properly. There are three key files involved: landing.component.html landing.component.scss landing.compone ...

Testing the angular unit for a partially functioning ternary condition

Can you help me troubleshoot an issue with my test case for a ternary function? It works fine for true conditions, but not for false ones. I'm not sure what's wrong with my logic. What changes should I make to fix it? public getData(ball: any) ...

Storing browser cookies in Azure Static Web App

I recently set up a solution on Azure with a web API in .NET 6 deployed to App Service, and a front-end application in Angular deployed to Azure Static Web App. I made sure to configure CORS on the back-end App Service to allow the front-end origin. Howeve ...

The protractor-jasmine2-screenshot-reporter seems to be failing to generate the necessary screenshots within the designated folder

I have encountered an issue with my protractor.conf.js file and need some assistance. I have created the target/screenshots folder manually in the root of my angular-cli project, but when I run protractor conf.js, the protractor tests in the browser window ...

Issue with displaying selected value and options in Mat-select when using formarray - Reactive forms in Angular

I've been working on the code below to create dropdowns, but I'm having trouble getting the selected value and options to show up in the dropdowns. Can you help me figure out what's wrong with the code? Component code testForm: FormGroup; ...

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...

The addition of special characters to strings in TypeScript through JavaScript is not functioning as expected

I need assistance on conditionally appending a string based on values from captured DOM elements. When the value is empty, I want to include the special character "¬". However, when I try adding it, I get instead because the special character is not reco ...

Unlock the encrypted information in the blockchain

I've been working on encrypting and decrypting values using Node's built-in crypto module. I found a helpful tutorial that showed me how to encrypt the data, but it didn't provide any sample code for decryption. When I tried using code from ...

How to assign a class specifically to a single row using Angular 2

I have a tab containing multiple rows, and I am trying to add a class to the current row when I click on my delete button. The delete button returns the id of the row that needs to be deleted. My issue is that I am unsure how to dynamically add a class to ...

Retrieving information from a .json file using TypeScript

I am facing an issue with my Angular application. I have successfully loaded a .json file into the application, but getting stuck on accessing the data within the file. I previously asked about this problem but realized that I need help in specifically und ...

Populate an Angular form using @Input to display data retrieved from a Firebase database through a service injection

I've encountered a challenge while working on an Ionic Angular project involving a form. The issue I'm facing is related to a component that serves as a form filled by an Input (Component). The problem seems to be that the form gets populated be ...

Typescript's Intersection Types: The Key to Overlapping Properties

Looking to create a type-safe utility function in Typescript 4.0 for comparing properties of two objects, my initial code snippet is below: export function propertiesMatch<O extends object, T extends O, S extends O>(first: T, second: S, props: (keyof ...

Agents should only be initialized within a before function or a spec in Angular

Having trouble with my private function: private GetChargesByClient(clientId: number): Observable<any[]> { const ds = new Date(); const dateTocompare = new Date(ds.setFullYear(ds.getFullYear() - 1)); return this.getCharges(id).pipe(map(res => re ...

Creating a realistic typewriter effect by incorporating Code Block as the input

I am looking to add a special touch to my website by showcasing a code segment with the Typewriter effect. I want this code block not only displayed but also "typed" out when the page loads. Unfortunately, I have been unable to find a suitable solution s ...

Break down Angular modules into smaller parts with the help of webpack

As I work on breaking down a huge Angular project with numerous components, I'm faced with the challenge of dealing with this large module that ideally shouldn't be there in the first place. Unfortunately, due to the current stage of the project, ...

Verify and retrieve information from the Dynamics CRM Web API with the help of Angular 2 (TypeScript)

How can one authenticate and query the Dynamics CRM Web API from a Single Page Application developed with Angular 2 (TypeScript)? Initial research indicates that: The Dynamics CRM (version 2016 or 365) instance needs to be registered as an application ...

What is the best way to verify the type of an object received from request.body in Typescript

Is it possible to check the object type from the request body and then execute the appropriate function based on this type? I have attempted to do so in the following manner: export interface SomeBodyType { id: string, name: string, [etc....] } ...

Verifying Whether Objects in TypeScript File Adhere to a Certain Interface

Currently, I am in the process of developing a procedure that scans through a collection of *.ts files within a directory to identify those containing a class that implements a specific interface. While my preference is to be able to detect multiple classe ...

Angular does not render components when the URL changes during navigation

I am attempting to create a simple routing functionality in an Angular application by navigating through components using button clicks. Although the URL path changes, the content within the component's view is not being rendered. I have set up the a ...

Tips for showcasing individual row information in a popup window with Angular 9

Here is the code snippet for utilizing the open dialog method in the component: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { AuthService } from '../_services/auth.se ...