Angular Material 2: Tips for Differentiating Multiple Sortable Tables in a Single Component

Greetings, esteemed members of the Stackoverflow community,

As per the Angular Material 2 documentation, it is mentioned that you can include an mdSort directive in your table:

Sorting

The mdSort directive enables a sorting user interface on the column headers of the table. The sort headers generate events that can be utilized to trigger an update through the table's data source.

Code : component.html

Utilizing the mdSort directive and the md-sort-headers

<md-table fxFlex="100%" #table [dataSource]="dataSource" mdSort>

              <ng-container mdColumnDef="category">
                <md-header-cell *mdHeaderCellDef md-sort-header> Category </md-header-cell>
                <md-cell (click)="alert(element)" *mdCellDef="let element"> {{element.category}} </md-cell>
              </ng-container>
             ...
             ...
</md-table>

Code: component.ts

Declaring the sort directive:

 @ViewChild(MdSort) sort: MdSort;

Injecting it into the datasource:

this.dataSource = new ExampleDataSource(this.exampleDatabase, this.sort);

And utilizing it to sort the objects:

getSortedData(): Task[] {
const data = this._exampleDatabase.data.slice();
if (!this._sort.active || this._sort.direction === '') { return data; }

return data.sort((a, b) => {
  let propertyA: number|string|boolean = '';
  let propertyB: number|string|boolean = '';

  switch (this._sort.active) {
    case 'category': [propertyA, propertyB] = [a.category, b.category]; break;
    case 'task': [propertyA, propertyB] = [a.task, b.task]; break;
    case 'favorite': [propertyA, propertyB] = [a.favorite, b.favorite]; break;
  }

  let valueA = isNaN(+propertyA) ? propertyA : +propertyA;
  let valueB = isNaN(+propertyB) ? propertyB : +propertyB;

  return (valueA < valueB ? -1 : 1) * (this._sort.direction === 'asc' ? 1 : -1);
});

}

Now, I have a need for another sortable table with its own datasource and database setup.

How can I distinguish between multiple mdSort directives effectively?

Answer №1

To bind to directives, you can use the exportAs attribute within the directive itself. Check out this resource for more information: Angular 2: Get reference to a directive used in a component

However, if you are working with a third-party library like MdSort, this method may not work as MdSort does not have the exportAs property.


If you need to bind to components, you can assign a unique ID to each table using hashtags:

<md-table fxFlex="100%" #table1 [dataSource]="dataSource1" mdSort>
</md-table>
<md-table fxFlex="100%" #table2 [dataSource]="dataSource2" mdSort>
</md-table>

Then, you can access these tables uniquely by referencing them like this:

@ViewChild('table1') table1: MdTable;
@ViewChild('table2') table2: MdTable;

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

Why does `react/require-default-props` still display an error even when a default prop value has been set?

This inquiry pertains to the guideline require-default-props. Here is the code snippet in question: function MyComponent({ blubb = 'my default', }: { blubb?: string, }) { // blubb defaults to 'my default' }; Eslint is flagging a ...

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 ...

Troubleshooting Typescript with Chrome when packaged by Webpack on Visual Studio 2017 using .NET Core 2.2

Many questions have been asked about debugger issues in Visual Studio 2017 with TypeScript and Webpack. Despite the common answer being that it should work by default, my debugger is still not functioning properly. I am new to TypeScript and Webpack, so I ...

Issue with importing aliases in Angular 7 production environment

Hello everyone! I have encountered an issue where using alias on import and building the project in production mode (--prod flag) results in the alias being undefined. Interestingly, this behavior does not occur in development mode. Any suggestions on how ...

Display a Carousel in Angular4 based on the selected value from a dropdown

My goal is to create a dynamic carousel that displays a football club's players when the user selects the team from a dropdown menu. The team options are loaded from a database, as well as the player information. Currently, I am able to retrieve the ...

Designing functional components in React with personalized properties utilizing TypeScript and Material-UI

Looking for help on composing MyCustomButton with Button in Material-ui import React from "react"; import { Button, ButtonProps } from "@material-ui/core"; interface MyButtonProps { 'aria-label': string, // Adding aria-label as a required pro ...

What could be causing IdentityServer 4 code flow to intermittently receive an invalid_grant response?

For my Angular application, I have implemented the identityserver4 code flow using the angular-oauth2-oidc library. Here is a snippet of my configuration: OauthConfig: AuthConfig = { issuer: 'http://mydomain.identityserver4', ...

Here is a guide on sorting through data within an array of objects using React.js and Typescript

How can I filter dealers' data based on the minimum and maximum price range of a slider change? I am retrieving dealers' data using an API and storing the slider's min and max values in a handle change function. What is the best way to filte ...

How do I use TypeScript and protractor to retrieve the column index of a grid by matching the header text of that column?

I have been attempting to create a function that can determine the column index of a grid based on the header text for that particular column. Despite several attempts, as shown in the comments below, the function consistently returns -1 instead of the exp ...

Typeorm encountered an error when attempting to assign the unknown type to an entity

I'm encountering difficulties while using TypeOrm with TypeScript for a specific project. It appears that TypeScript is unable to recognize a type being returned from a TypeORM entity. @Entity({ name: "users", synchronize: false }) export default c ...

When using RxJS forkjoin, it will cease subscription if there is a flatMap present within one of the observables it is awaiting

I have been experimenting with nested calls using rxjs and trying to implement nested forkJoins. However, I have encountered an issue where the outer forkJoin stops returning a result when there is a flatMap inside the inner observable. Here is a snippet ...

Encountering difficulties redirecting to the homepage following Facebook login

After successfully logging in with Facebook, I am having trouble redirecting to my home page. The token is stored in localStorage, but it remains on the login page without redirecting. loginWithFB() { this.facebook.login(['public_profile', &a ...

How to access the template html in Angular 8 (or 9) before compilation

I'm working on developing a "help center" for my colleagues in the development team, providing guidance on using components and more. My goal is to create a component that displays both the output and the code used to generate it, like this: <app ...

Tips for linking a column value in a data table with Angular 7

I have an application where I retrieve data in a table format. This front end of this application is built on angular7. Now, I need certain column values to be links that when clicked will display a new component. For example: Column1 Column2 ...

The origin of the Angular img src becomes blurred when invoking a function

I want to dynamically change the image src by calling a function that returns the image path. However, when I attempt to do so using the code below, the image element displays as <img src(unknown)/> component.ts: getMedia(row) { this.sharedData ...

Steps for displaying API Response in a material-table

In my project, I have a component named List which displays data using mat-cards. When a specific mat-card is clicked, it navigates to another component called home. In this home component, the data from the selected mat-card is displayed within another ma ...

Purge the localStorage every time the page is refreshed in Angular 2

After successful authentication, I am storing a token in localStorage. However, every time I refresh the page, I need to delete the token and redirect to a specific router. I'm struggling to find a way to achieve this in Angular, so currently I' ...

Element without style

In my app, I have implemented numerous material design components, but there are two input elements for which I would like to customize the style and remove the default material design look. Is there a way to eliminate the CSS styling from an <input ma ...

Executing the plugin-typescript library within an Angular 2 project hosted on localhost

I am encountering an issue every time I run my angular2 project where numerous files are being loaded, including the 'ts' library from unpkg.com/plugin-typescript/lib/plugin.js. I am looking to eliminate the need for this file to load from anothe ...

Include an arrow in a personalized horizontal scroll bar using Angular and HTML

After styling a horizontal scrollbar for my chartjs graph, I attempted to add arrows using material icons like <mat-icon>keyboard_arrow_left</mat-icon>. However, I am struggling to align them next to the left and right of the scrollbar. Can any ...