The column sorting functionality for the 'Total' column in an Angular mat-table is not functioning properly

Everything seems to be working smoothly with my mat table, except for the last column that is supposed to calculate the sum values from the other columns using the reduce method.

I'm facing a bit of a roadblock with this issue. Initially, I thought that the problem might be due to the fact that the reduce method is executed after the OnInit lifecycle event. However, even when I tried declaring this.dataSource.data = this.data in ngAfterViewInit, it didn't work.

This is how I have structured my HTML template:

<div [ngClass]="{'hidden': !hasData()}">
  <div class="subcollection-name">{{subCollection.name}}</div>
  <div class="table-container">
    <table
      matSort
      mat-table
      class="items-table"
      [dataSource]="dataSource"
    >
      <!-- Code for different table columns -->
    </table>
  </div>
  <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
</div>

And this is how my TypeScript file looks like:

import { Observable, BehaviorSubject } from 'rxjs';
import { SubCollection } from 'model/item-tree/collection';
import { MatSort, MatPaginator, MatTableDataSource } from '@angular/material';
import { Component, ViewChild, Input, OnInit, ChangeDetectionStrategy, AfterViewInit, OnChanges } from '@angular/core';

@Component({
  selector: 'app-collection-steps-report-subcollection-table',
  templateUrl: './collection-steps-report-subcollection-table.component.html',
  styleUrls: ['./collection-steps-report-subcollection-table.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CollectionStepsReportSubcollectionTableComponent implements OnInit {

  // TypeScript component properties and methods defined here
}

If anyone has any helpful insights or tips to resolve this issue, I would greatly appreciate it! Thanks in advance!

Answer №1

After several attempts, I discovered that the reason for my issue was that the 'total' column was not part of the 'item' object.

Therefore, I incorporated a map function into my data processing, where I assigned the result of the getTotalDataOfItem function to a new array of data within the ngOnInit method, and it resolved the issue!

Now that the 'total' column is present in my item, I needed to modify the HTML template to display item.total in the <td> instead of calling getTotalDataOfItem(item.id)

To ensure everything functions correctly, simply insert this code within the ngOnInit section of the TS file

const dataWithTotal = this.data.map(
  item => {
    return {
      ...item, total: this.getTotalDataOfItem(item['id'])
    };
  }
);

Next, adjust the HTML file as follows

<td mat-cell *matCellDef="let item">{{ 'stepsReportAverageTimeSpentDaysUnit' | translate:{ numberDays: item.total } }}</td>

Now you can enjoy your mat-table sorting all columns correctly :)

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

What is the process for starting Nx serve for an application that has lint errors?

After receiving an nx Angular project, I noticed that there are lint rules in place. Executing nx run shell:lint displays all the errors and warnings specified in the .eslintrc.json configuration file. However, when running nx run shell:serve, the build ...

Developing a project using npm and Node.js with Typescript has been smooth sailing so far. However, an issue has arisen

Recently, I came across a helpful guide on setting up a Node.js project in Typescript on this website: https://basarat.gitbooks.io/typescript/docs/quick/nodejs.html The guide also provides instructions for auto-recompilation upon changes when using npm st ...

Should the input field only contain spaces, a validation error will be triggered by the user

I am currently working on an Angular form implementation that allows users to enter their phone numbers. I have integrated a custom directive called appPhoneExtMask for formatting the phone numbers and have also implemented Angular form validation for both ...

Zod: ensure at least one field meets the necessary criteria

Currently, I am in the process of developing a form that allows users to input either their email address or phone number. While they have the option to provide both, they are required to enter both before proceeding. For this project, I am utilizing Zod a ...

fp-ts/typescript steer clear of chaining multiple pipes

Is there a more concise way to handle nested pipes in fp-ts when working with TypeScript? Perhaps using some form of syntactic sugar like Do notation? I'm trying to avoid this kind of nested pipe structure: pipe( userId, O.fold( () => set ...

Is there a way to bypass the subscription confirmation?

One of the challenges I am facing involves a stream of data changes that is emitted: interface Data { id: number, prop: string } This stream is then altered by another stream that sends an HTTP request. At the end, I subscribe to the response: .subsc ...

The background image causes the scrollbar to vanish

As a beginner, I am in the process of creating a web page that features a consistent background image. However, I have encountered an issue where the scroll bar does not appear on a specific page called "family details" due to the background image. I atte ...

Receiving a reply from the axios function

Whenever I try to call the lookUpItem function from ItemSearch.vue, I always get an undefined response. Code snippet from ItemSearch.vue: <script setup lang="ts"> import { lookUpItem } from '../systemApi' async fu ...

Unforeseen Problem: Mocha ES6 Node App Glitch

Encountering an ES6 import issue in Mocha test cases currently. Even after attempting to add the latest Babel and presets, the issue remains unresolved. Various solutions have been tested but none seem to fix the problem. This snippet shows my package.jso ...

Attach an event listener to a particular textarea element

Currently, I am developing a project in Next.js13 and my focus is on creating a custom textarea component. The goal is to have this component add an event listener to itself for auto-adjusting its height as the user types. Below is the relevant section of ...

Utilize ctrl+z and bg or the & signal when handling background processes in shell scripting

Within my script, I am running the following commands: cd $1 ng s --host 0.0.0.0 --port 4200 ...additional commands ... I need to execute an Angular project within this script. However, when running the script from a micro-service, it does not return a r ...

What type of value does a `use` directive return?

Upon reviewing the svelte tutorial, I observed that the clickOutside function provides an object with a destroy method. What should be the precise return type of a custom use directive? export function clickOutside(node: HTMLElement): ??? { // Initia ...

Place an image at the top of the canvas at a specific location

Currently, I am in the process of reconstructing this specific website My approach involves working with React (similar to the aforementioned site) and utilizing the same cropper tool that they have implemented. For cropping, I am incorporating react-imag ...

Tips on showcasing an array as a matrix with a neat line property

I am currently developing an application using TypeScript, and utilizing a JSON array structured like this: data = [{"name":"dog", "line":1}, {"name":"cet", "line":1}, ...

JavaScript => Compare elements in an array based on their respective dates

I have an array consisting of more than 50 objects. This array is created by concatenating two arrays together. Each object in this array contains a 'date' key with the date string formatted as: `"2017-03-31T11:30:00.000Z"` Additionally, there ...

Divide Angular component unit test involving asynchronous tasks

One of my components is responsible for fetching data from a server using a service and then displaying it. I have created a test for this component which ensures that the data is loaded correctly: ... it('Should contain data after loading', as ...

Binary encounters an issue: Error - Module failed to self-register

Binary file saved to the specified directory Caching binary for future use [email protected] during postinstall node script execution. The system attempted to locate the relevant binary but encountered an error: Module did not self-register. This iss ...

Receiving an `Invalid module name in augmentation` error is a common issue when using the DefaultTheme in Material

After following the guidelines outlined in the migration documentation (v4 to v5), I have implemented the changes in my theme: import { createTheme, Theme } from '@mui/material/styles' import { grey } from '@mui/material/colors' declar ...

Guide to manually triggering a re-render of a component in Angular 2

While working with ng Smarttable, I encountered a situation where I needed to change the datasource array through an event, specifically by altering an ID within the array. Strangely, Angular did not detect these changes until I interacted with the page by ...