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

Adding Font Awesome to my Angular 12 project within Visual Studio 2019

Seeking a no-frills guide for integrating Font Awesome (free version) into my Angular 12 application within Visual Studio 2019. After countless Google searches, I am bombarded with intricate methods. It's baffling why such complexity exists just to in ...

Vuetify 3 does not display dialogs

I am attempting to integrate vuetify 3.alpha with vue 3. Below are the files I am working with: Temp.vue (obtained from vuetify example) <template> <div class="text-center"> <v-dialog v-model="dialog" w ...

What is the best way to pass a full object from an Angular 2 dropdown list to the service?

Is it possible to return an object from a dropdown list to the service? I would like to be able to get the component object whenever I click on an item in onChangeForComponent. <select [ngModel]="selectedDev" (ngModelChange)="onChangeForComponent($eve ...

Tips on using class-validator @isArray to handle cases where only a single item is received from a query parameter

Currently, I am attempting to validate a request using class-validator to check if it is an array. The inputs are sourced from query parameters like this: /api/items?someTypes=this This is what my request dto resembles: (...) @IsArray() @IsEn ...

What is the best way to store items in localStorage within Angular version 4.4.6?

I have been working on implementing a basic authentication system in Angular 4.4 with MongoDB as the backend database. login.component.ts import { Component, OnInit } from '@angular/core'; import { AuthService } from 'app/services/auth.ser ...

When attempting to import css-animator in Angular2/Typescript, a 404 error is displayed, indicating that the

Recently, I delved into the world of Angular2 and decided to experiment with some animations using css-animator package.json "dependencies": { "@angular/common": "2.0.0-rc.3", "@angular/compiler": "2.0.0-rc.3", "@angular/core": "2.0.0-rc.3", ...

In TypeScript Next.js 14 APP, object literals are limited to declaring existing properties

I encountered an error in my typescript next.js 14 APP. I need assistance resolving this issue, which states: Object literal may only specify known properties, and 'productPackages' does not exist in type '(Without<ProductCreateInput, Pr ...

Can we determine the type signature of useCallback for an event handler by inference?

Currently, I am working with TypeScript and React to implement a callback function using an arrow function on a Material UI <Select> component: import React from 'react'; import MenuItem from '@material-ui/core/MenuItem'; import ...

Unexpected behavior: ng2-dragula modelDrop event leading to undefined array

Struggling to figure out the issue with this code. As shown in this GIF, when dragging a div from one container to another, the object disappears and the array becomes undefined. https://i.stack.imgur.com/TELyc.gif Here is the code snippet: Main View.ht ...

Error message: "Encountered a template parsing error stating that the element 'ngb-carousel' is not recognized."

Initially, I created a fresh project using the Angular CLI by running this command: ng new my-project Next, I followed the instructions in the angular-cli readme to install Bootstrap 4. After that, I installed NG Bootstrap. Then, I generated a new comp ...

`It is important to note that in Tailwind CSS, `h-8` does not supersede `h-4

I developed an Icon component that looks like this: import { IconProp, library } from "@fortawesome/fontawesome-svg-core"; import { far } from "@fortawesome/free-regular-svg-icons"; import { fas } from "@fortawesome/free-solid-svg- ...

Setting up roles and permissions for the admin user in Strapi v4 during the bootstrap process

This project is built using Typescript. To streamline the development process, all data needs to be bootstrapped in advance so that new team members working on the project do not have to manually insert data into the strapi admin panel. While inserting ne ...

What is the best way to separate a string using a comma as a delimiter and transform it into a string that resembles an array with individual string elements

I am in search of a way to transform a string, such as: "one, two, three, four" into a string like: "["one", "two", "three", "four"]" I have been attempting to devise a solution that addresses most scenarios, but so far, I have not been successful. The ap ...

the Sprite fails to appear on the screen

Can you help me figure out how to fix the issue I'm having with loading images in this component? Currently, when I refresh the page, the image does not load properly and appears resized to 1 pixel width. Should I wait for the image to fully load befo ...

Errors in the @babel/types during the ng build process in Angular version 8.2.14

When I execute the command 'ng build' for my Angular App, I encounter the following errors: ERROR in ../node_modules/@types/babel-types/index.d.ts:1769:96 - error TS1144: '{' or ';' expected. 1769 export function assertArrayE ...

What is the best way to implement a switch case for the value of a property within an object in a TypeScript file?

The object I'm dealing with looks like this: {a: auth?.type === '1' || auth?.type === '2' || auth?.type === '3' ? { reason: // I need to implement a switch case here : un ...

Error: Unable to retrieve options using this.getOptions function. This issue is unrelated to Vue, it is occurring within

Required Modules "dependencies": { "express": "^4.17.1", "express-static-gzip": "^2.1.1", "react": "^17.0.2", "react-dom": "^17.0.2", "reac ...

The issue arises when the ngif directive is triggered by the scrollDispatcher, causing the variable

While using Angular, I encountered an issue where the DOM (ngIf) was not responding to a variable flag change that was being triggered by scrollDispatcher for scrolling detection. Below is the code snippet of my testing: // html <div *ngIf="scrollS ...

Having difficulty sending a message from an AngularJS application to an Angular 10 application through an iframe

I have two applications running locally - one is an AngularJS application and the other is an Angular 10 application. I am trying to access a page from the Angular 10 application using an iframe and send a message to it from the AngularJS application. How ...

How to extract and compare elements from an array using Typescript in Angular 6

I have created a new Angular component with the following code: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Compone ...