The issue with sorting in Angular 8 mat tables persists when dealing with multiple tables

As a newcomer to Angular, I am still learning and have encountered an issue with sorting in the mat table. I have multiple tables on one page, each separated by a mat tab. The problem is that sorting only works on the first table ("crane master list") in the first tab, while the rest do not respond.

TS

import { MatSort, Sort } from '@angular/material/sort';

  @ViewChild(MatSort, { static: true }) sortCrane: MatSort;
  @ViewChild(MatSort, { static: true }) sortLifeboat: MatSort;

 preloadData() {
    //fetch data from api
    this.masterlistService.getCrane().subscribe(res => {
      this.craneDataSource = new MatTableDataSource(res);
      this.craneDataSource.sort = this.sortCrane;
    });
    this.masterlistService.getLifeboat().subscribe(res => {
      this.lifeboatDataSource = new MatTableDataSource(res);
      this.lifeboatDataSource.sort = this.sortLifeboat;
    });
}

HTML

<mat-tab-group style='min-height:37rem;' (selectedTabChange)="onClickTab($event)">
 <mat-tab label="Crane Masterlist">
      <table mat-table [dataSource]="this.craneDataSource" class="mat-elevation-z8" style="margin-top: 3.5rem;" matSort  (matSortChange)="announceSortChange($event)">
   <ng-container matColumnDef="Region">
          <th mat-header-cell *matHeaderCellDef class="thead-dark" mat-sort-header> Region </th>
          <td mat-cell *matCellDef="let item"> {{item.Region}} </td>
        </ng-container>
//....etc
</table>
  </mat-tab>
 <mat-tab label="Lifeboat Masterlist">
       <table mat-table [dataSource]="this.lifeboatDataSource" class="mat-elevation-z8" style="margin-top: 3.5rem;"
        matSort (matSortChange)="announceSortChange($event)">
   <ng-container matColumnDef="Region">
          <th mat-header-cell *matHeaderCellDef class="thead-dark" mat-sort-header> Region </th>
          <td mat-cell *matCellDef="let item"> {{item.Region}} </td>
        </ng-container>
//....etc
</table>
  </mat-tab-group>
  </mat-tab>

Answer №1

If you have multiple instances of matSort in a single file, simply using the class name with @ViewChild will not suffice. Instead, opt for a template reference variable.

<table #craneTable mat-table [dataSource]="this.craneDataSource" class="mat-elevation-z8" style="margin-top: 3.5rem;" matSort  (matSortChange)="announceSortChange($event)"><!-- ... --></table>
<table #lifeboatTable mat-table [dataSource]="this.lifeboatDataSource" class="mat-elevation-z8" style="margin-top: 3.5rem;" matSort (matSortChange)="announceSortChange($event)"><!-- ... --></table>

  @ViewChild("craneTable") sortCrane: MatSort;
  @ViewChild("lifeboatTable") sortLifeboat: MatSort;

Another option is to utilize @ViewChildren

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

Creating a return type in TypeScript for a React Higher Order Component that is compatible with a

Currently utilizing React Native paired with TypeScript. Developed a HOC that functions as a decorator to add a badge to components: import React, { Component, ComponentClass, ReactNode } from "react"; import { Badge, BadgeProps } from "../Badge"; functi ...

Is there a way to prevent an item from being selected in a Select component when the first letter of the option is pressed?

I'm currently working with the material UI Select component and I'm attempting to create a filter within it that will only display items matching the user's input. Below is a simplified example of my current project: function App() { con ...

Exploring the world of HTTP PUT requests in Angular 4.0

I have encountered an issue with a function I wrote for sending an http put request to update data. The function is not receiving any data: updateHuman(human: Human) { const url = `${this.url}/${human.id}`; const data = JSON.stringify(human); ...

What should be done in the absence of any subscriptions?

Incorporating a generic HTTP service to encapsulate certain HTTP behaviors is part of our system. In case of an error, we include the error in a BehaviorSubject. I am contemplating on whether there is a method to display this error only if no one is subsc ...

Is there a specific function that is triggered upon the successful completion of a subscription process?

I am facing an issue with the code below. The navigation is happening when a customer is created, instead of waiting for the address to be created successfully. Any assistance on this matter would be greatly appreciated. createCustomer(model: any) { ...

Is there a different term I can use instead of 'any' when specifying an object type in Typescript?

class ResistorColor { private colors: string[] public colorValues: {grey: number, white: number} = { grey: 8, white: 9 } } We can replace 'any' with a specific type to ensure proper typing in Typescript. How do we assign correct ...

Inheriting static attributes in Typescript without using the static keyword

My project involves utilizing multiple classes that represent entities from a database. abstract class Entity { static columns: Column[]; static showInNav: boolean; static dependencies: string[]; // non-static fields } class Entity_A exten ...

Is the Inline Partial<T> object still throwing errors about a missing field?

I recently updated to TypeScript version ~3.1.6 and defined an interface called Shop as follows: export interface Shop { readonly displayName: string; name: string; city: string; } In this interface, the property displayName is set by the backend a ...

How come the hook keeps triggering endlessly in a loop when I try to pass the updated props?

I've encountered an issue with a custom hook I created for making HTTP requests. The problem is that the request seems to be firing in an endless loop, and I'm unsure of what's causing this behavior. My intention is for the request to only t ...

Contrasting input: [] with the @Input() directive

Recently, I've begun exploring the world of child and parent component communication in Angular 4. In my research, I stumbled upon older videos that utilize the input: [] syntax instead of the now more prevalent @Input() syntax. Is there any distincti ...

Tips for successfully passing store state as a prop in React-Redux with TypeScript

Having trouble passing information from the initial state of the store to a component where it's supposed to be rendered. Despite a console.log in the component showing that it's undefined, there doesn't seem to be any issue with the initial ...

Issue encountered when trying to use Array.sort() method to sort an array of objects

I'm facing an issue sorting an array of objects by a name property present on each object. When utilizing the sort() method with the given code snippet, I encounter the following error: ERROR ReferenceError: b is not defined This is my code block: m ...

In TypeScript, how to refer to the type of the current class

Is there a way to reference the current class type in the type signature? This would allow me to implement something like the following: export class Component{ constructor(config?: { [field in keyof self]: any }) { Object.assign(this, config) ...

Is there a way in Jest to restrict function calls to only those that are expected and disallow any other unauthorized calls

When working with Jest, you have the ability to mock out and spy on function calls within a function using functionalities like jest.spyOn and jest.fn() with .toHaveBeenCalledTimes(1) etc. However, in Spock framework testing, you can conclude your unit tes ...

Having difficulty deploying the ASP.Net application in Visual Studio

While attempting to publish my app from Visual Studio, I encountered the following error: The command "node node_modules/webpack/bin/webpack.js --env.prod" exited with code 1. First Azure app C:...\firstazureapp C:...firstazureapp\firstaz ...

What's the best way to utilize the tsconfig.json "types" field within a monorepository setting?

Part 1 - Utilizing the "types" Field When a TypeScript library like library A provides type definitions alongside its normal exports, it looks like this: declare global { function someGlobalFunction(): void; } Library B depends on the type definitions ...

The Mongoose getter function is triggering error TS2590 by generating a union type that is too intricate to be displayed

I've come across the TS2590: Expression produces a union type that is too complex to represent error while trying to compile TypeScript. The issue seems to be connected to the id's getter function idFromString, as removing the id getter prevents ...

Unable to trigger (ngModelChange) event from within a div element in Angular 2

My app.component.ts contains the following code: public sendData(data: any) { console.log(data); } The code in app.component.html looks like this: <div type="text" contenteditable="true" (ngModelChange)="sendData($event)" [innerHTML]="childS ...

Having trouble getting webpack to transpile typescript to ES5?

Despite following official guides and various tutorials, I am still facing an issue with compiling my code to ES5 using TypeScript and webpack. The problem is that the final bundle.js file always contains arrow functions. Here is a snippet from my webpack ...

Tips for refreshing the apollo cache

I have been pondering why updating data within the Apollo Client cache seems more challenging compared to similar libraries such as react-query. For instance, when dealing with a query involving pagination (offset and limit) and receiving an array of item ...