utilizing mat-sort-header on a table column displaying the size of a nested array attribute within every record

Imagine I have a MatTableDataSource that is created using the following array:

[ {propA: 'something', propB: ['a', 'b', 'c']}, {propA: 'somethingElse', propB: ['d', 'e', 'f']}]

This array consists of objects where propB is an array.

Now, for each element in the outer array, I would like to display a row in my table with two columns: propA (displaying the value of this property) and propBCount (showing the length of the array for this property).

Below is the column definition for the second column I desire:

<ng-container matColumnDef="propBCount">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Total Items </th>
        <td mat-cell *matCellDef="let element"> {{element.propB.length}} </td>
</ng-container>

How can I implement mat-sort-header for this particular column?

Answer №1

According to the documentation on sorting in the Table section of Angular Material:

If the data properties do not align with the column names or if a more complex data property accessor is needed, a custom sortingDataAccessor function can be used to override the default data accessor on the MatTableDataSource.

  1. Add the matSort directive to the mat-table HTML element.
<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
  ...
</table>
  1. Assign MatSort to the dataSource.
  2. Implement the custom sorting logic for dataSource.sortingDataAccessor.
@ViewChild(MatSort) matSort: MatSort;

ngAfterViewInit() {
  this.dataSource.sort = this.matSort;
  this.dataSource.sortingDataAccessor = (data: any, sortHeaderId: string) => {
    if (sortHeaderId == 'propBCount') return data.propB.length;

    return data[sortHeaderId as keyof typeof data];
  };
}

Check out the demo on StackBlitz

For more information, visit: Angular mat-table sort example: Adding sorting to the material table

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

Can ngx permissions in angular be trusted for ACL management?

Currently working with Angular 6 and looking to manage user access control. While the conventional wisdom is to handle ACL in the backend, there are packages like ngx permissions available for managing it on the frontend. Is it secure to utilize these fe ...

Dealing with server-side errors while utilizing react-query and formik

This login page utilizes formik and I am encountering some issues: const handleLogin = () => { const login = useLoginMutation(); return ( <div> <Formik initialValues={{ email: "", password: "" }} ...

Is it possible to export an imported merged namespace in Typescript?

Within my library, I have a collection of merged declarations setup like this: export class Foo {...} export namespace Foo { export class Bar {...} ... } export default Foo These merged declarations often contain inner classes and specific errors r ...

What is the best way to create a T-shaped hitbox for an umbrella?

I've recently dived into learning Phaser 3.60, but I've hit a roadblock. I'm struggling to set up the hitbox for my raindrop and umbrella interaction. What I'd love to achieve is having raindrops fall from the top down and when they tou ...

In Next.js, a peculiar issue arises when getServerSideProps receives a query stringified object that appears as "[Object object]"

Summary: query: { token: '[object Object]' }, params: { token: '[object Object]' } The folder structure of my pages is as follows: +---catalog | | index.tsx | | products.tsx | | | \---[slug] | index.tsx | ...

Error occurs when attempting to call Angular from NodeJS

I am trying to integrate Angular with Node.js, but I'm encountering an error while accessing it in the browser. Angular works fine when I run "node server." Error: runtime.js:1 Uncaught SyntaxError: Unexpected token < polyfills.js:1 Uncaught Synt ...

How to handle the "subscribe doesn't exist on type void" error when trying to subscribe to data from a service?

I am currently working on an Angular 7 application and I have encountered an error stating that the property 'subscribe' does not exist on type void when trying to subscribe to data from a service. The error is displayed in the subscribe data fu ...

The Angular performance may be impacted by the constant recalculation of ngStyle when clicking on various input fields

I am facing a frustrating performance issue. Within my component, I have implemented ngStyle and I would rather not rewrite it. However, every time I interact with random input fields on the same page (even from another component), the ngStyle recalculate ...

The error message "unit test undefined is not an object (evaluating 'this.groups.map')" indicates a problem with the mapping function

Currently, I am working with this script: groups: Group[] = [] constructor( ) { this.groups = AuthenticationService.getUserGroups() let menuList: any = [] this.groups.map((permission: Group) => { menuList.push(...this.menuGene ...

The current context for type 'this' cannot be assigned to the method's 'this' of type '...'

Currently, I am in the process of defining type definitions (.d.ts) for a JavaScript library. In this specific library, one of the methods accepts an object of functions as input, internally utilizes Function.prototype.bind on each function, and then expos ...

What is the process for retrieving an element from component interaction?

Is there a way to dynamically change the background color based on component interaction? I am looking for a method to compare the target element with the current element. For example, here is a hypothetical scenario: <span [style.background]=" ...

Exploring Uppercase and Lowercase Filtering in NGXS for Angular Developers

I am encountering a problem with filtering and searching, specifically in matching the exact lowercase or uppercase of the string. Is there a way to search or filter regardless of the case sensitivity? For more information, please visit this link CLICK H ...

Is there a method to create a typecheck for hasOwnProperty?

Given a certain interface interface Bar { bar?: string } Is there a way to make the hasOwnProperty method check the property against the defined interface? const b: Bar = { bar: 'b' } b.hasOwnProperty('bar') // works as expected b. ...

Select three random items from a string array list along with their corresponding indexes using TypeScript in Angular

Consider this example: I am working with a string array const groceries = [ 'milk', 'coriander', 'cucumber', 'eggplant', 'carrot', 'brinjal', 'on ...

Is it necessary to include both `import 'rxjs/Rx'` and `import { Observable } from '@rxjs/Observable'` in my code?

import { Injectable } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import { Observable } from '@rxjs/Observable'; import 'rxjs/Rx'; import 'rxjs/add/observable/throw'; @Com ...

Tips for implementing the click outside feature on mobile iOS using Angular's @HostListener

It seems to work fine everywhere except on iPhones. When I try it on my mobile iPhone, it doesn't function properly. @HostListener('document:click', ['$event.target']) public onClick(targetElement: HTMLElement): void { ...

Exploring the inner workings of Angular v4.4 and gaining insight into the roles of platformBrowserDynamic and PlatformRef

Recently, I have come into possession of an Angular 4.4 application that utilizes Webpack v3.5 and TypeScript v2.3.3. Struggling to decipher the imported code, I am at a loss understanding its functionality and correctness. To simplify matters for analysis ...

The vertical bar chart from amcharts is lacking labels

The graph attached displays labels alternatively, which appears to be a default setting of the amcharts. Is there a way we can modify it to show all the labels? Refer to the screenshot provided below. The implementation is done using amcharts in angular c ...

Enhancing collaboration: Seamlessly sharing interface/interface/model files in the integration of

Currently, I am engrossed in developing an application with an Express backend and Typescript whilst utilizing Angular for the frontend. The only snag I'm facing is that I require interface/models files from the backend to be accessible on the fronten ...

Exploring how Angular components can receive input values without the need for two-way

I've implemented an Angular 10 component like this: import { Component, Input, OnInit } from '@angular/core'; @Component({ selector: 'app-summary', templateUrl: './summary.component.html', styleUrls: ['./summa ...