What is the best way to display the arrows on a sorted table based on the sorting order in Angular?

I need assistance with sorting a table either from largest to smallest or alphabetically.

Here is the HTML code of the section I'm trying to sort:

 <tr>
                     <th scope="col" [appSort]="dataList" data-order="desc" data-name="no">
                         <span (click)="sort()" class="sort-icon d-flex"> No
                            <mat-icon *ngIf="sorting === 'desc'">keyboard_arrow_down</mat-icon>
                             <mat-icon *ngIf="sorting === 'asc'">keyboard_arrow_up</mat-icon>
                         </span>
                     </th>
                     <th scope="col" [appSort]="dataList" data-order="desc" data-name="id">
                         <span (click)="sort()" class="sort-icon d-flex">Id
                             <mat-icon *ngIf="sorting === 'desc'">keyboard_arrow_down</mat-icon>
                             <mat-icon *ngIf="sorting === 'asc'">keyboard_arrow_up</mat-icon>
                         </span>
                     </th>
                     <th scope="col" [appSort]="dataList" data-order="desc" data-name="type">Tür</th>
                     <th scope="col" [appSort]="dataList" data-order="desc" data-name="additional">Ek</th>
                     <th scope="col" [appSort]="dataList" data-order="desc" data-name="media">Medya
                     </th>
                 </tr>

**Additionally, here is the related TypeScript function:**

 sorting = "desc"
 sort() {
        if (this.sorting == "desc") {
            this.sorting = "asc"
        } else {
            this.sorting = "desc"
        }
    }

I am facing an issue where when I sort by 'NO', the arrow in 'ID' also moves. How can I resolve this problem?

My preference is that clicking on 'NO' should only affect the arrow there and not interfere with 'ID'.

Note: This is my first query here, so feedback is appreciated if I have overlooked anything.

Answer №1

If you are unsure about looping through it, this solution should work for you. I have utilized the basic structure from your code without installing all the modules to provide an idea.

<th scope="col"  data-order="desc" data-name="no">
  <span (click)="sort('no')" class="sort-icon d-flex"> No
     <span *ngIf="sorting['no'] === 'desc'">↑</span>
      <span *ngIf="sorting['no'] === 'asc'">↓</span>
  </span>
</th>
<th scope="col"  data-order="desc" data-name="id">
  <span (click)="sort('id')" class="sort-icon d-flex">Id
      <span *ngIf="sorting['id'] === 'desc'">↑</span>
      <span *ngIf="sorting['id'] === 'asc'">↓</span>
  </span>
</th>
<th scope="col"  data-order="desc" data-name="type">Tür</th>
<th scope="col"  data-order="desc" data-name="additional">Ek</th>
<th scope="col"  data-order="desc" data-name="media">Medya
</th>

sorting = { no: 'desc', id: 'desc' };
  sort(key: any) {
    if (this.sorting[key] == 'desc') {
      this.sorting[key] = 'asc';
    } else {
      this.sorting[key] = 'desc';
    }
  }

The key idea is to store the sorting of each column separately, either within the data source itself or in a separate object like I have demonstrated in the example provided.

I hope this explanation proves helpful.

For demonstration, refer to this working example. Stackblitz example

Answer №2

If you find that you are missing the necessary step, make sure to include private _cd: ChangeDetectorRef, in the component constructor.

Then update your sort function with the following:

 sorting = "desc"
 sort() {
   this.sorting = (this.sorting == "desc") ? "asc" : "desc"; 
   this._cd.markForCheck();
 }

Answer №3

The solution to your query will vary depending on the specific requirements you have. If you need the table to be sorted by two columns simultaneously, you can follow the instructions provided by @tarun-bhati and ensure that the sorting mechanism is functioning accordingly.

However, if you only want the table to be sorted by a single column at a time, you can implement the following approach:

  sortOrder: string;
  sortByColumn: string;
  sortData(column: string) {
    if (this.sortOrder === 'desc') {
      this.sortOrder = 'asc';
    } else {
      this.sortOrder = 'desc';
    }
    this.sortByColumn = column;
  }

You can then utilize these parameters in conjunction with appropriate conditions for the sort icons.

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

Utilize a generic data type for a property that can accept values of type 'number', 'string', or 'undefined'

This query involves React code but pertains to typescript rather than react. To simplify, I have a component called MyList which accepts a single generic type argument passed to the props type. The generic type represents an object that will be used to c ...

Efficient configuration for pnpm monorepo with TypeScript, vite, and rollup

Struggling to set up a monorepo using pnpm workspaces with typescript, vite for frontends, and rollup for backend microservices. Here's the current project structure: package.json <== all dependencies reside here tsconfig ...

Angular Typescript subscription value is null even though the template still receives the data

As a newcomer to Angular and Typescript, I've encountered a peculiar issue. When trying to populate a mat-table with values retrieved from a backend API, the data appears empty in my component but suddenly shows up when rendering the template. Here&a ...

Remove the Prisma self-referencing relationship (one-to-many)

I'm working with this particular prisma schema: model Directory { id String @id @default(cuid()) name String? parentDirectoryId String? userId String parentDirectory Directory? @relation("p ...

When 'Interval.after' is invoked within the library, Luxon throws an error message stating "Invalid Interval."

Encountering a strange issue with Luxon when the Interval.after method is invoked within the library. const interval = Interval.after(dateTime, duration); The following log pertains to the application DateTime__Duration, with the second line representing ...

Having trouble reaching the unidentified function

There are two different scenarios where the 3rd party library (BrowserPrint.js) is used; FUNCTIONAL ENV - JS and jQuery with the 3rd party libraries included simply in the <head> section of the document and the main function being called in $(do ...

Encountering the error "TS(2604): JSX element type 'App' does not have any construct or call signatures" while trying to export an array of JSX Elements

I have a function that returns an array of JSX Elements. When I pass this to ReactDOM.render, I encounter the error mentioned above. wrappers.tsx const FooterWithStore:React.FC = () => ( <Provider store={store}> <FooterLangWrapper ...

Is it possible to access the passed arguments in the test description using jest-each?

Utilizing TypeScript and Jest, consider this sample test which can be found at https://jestjs.io/docs/api#testeachtablename-fn-timeout it.each([ { numbers: [1, 2, 3] }, { numbers: [4, 5, 6] } ])('Test case %#: Amount is $numbers.length =&g ...

In just a single line of code, you can iterate through a Record object and retrieve an array of DOM elements

I am working with an object type MyType = 'name' | 'base' | 'six'; obj: MyType = { 'name': {key: 'm1'}, 'base': {key: 'm2'}, 'six': {key: 'm3'}, } My goal is ...

Utilizing the Double Mapping Feature in React with Typescript

It seems I might be overlooking something, can someone guide me on how to properly double map in this scenario? I'm encountering an error on the second map: Property 'map' does not exist on type '{ departure: { code: string; name: strin ...

Is it possible to alter the meaning of a word using the ngIf condition?

As a newcomer to Angular and Ionic, I am experimenting with retrieving JSON data from a URL and translating the words received to another language. My initial attempt using ngif did not yield the desired result! This is what I tried to do in order to chan ...

SyntaxError: Unexpected token '<' in Angular 6

I have been working on an angular website project. Here is the package.json file for my production environment: "dependencies": { "@angular/animations": "^5.0.2", "@angular/cdk": "^5.1.0", "@angular/common": "^5.0.2", "@angular/compiler": ...

Can someone provide guidance on effectively implementing this JavaScript (TypeScript) Tree Recursion function?

I'm currently grappling with coding a recursive function, specifically one that involves "Tree Recursion". I could really use some guidance to steer me in the right direction. To better explain my dilemma, let's consider a basic example showcasi ...

Save solely the timing information in Mongodb

Looking for advice on storing time values in MongoDB? Users will be inputting times as strings, such as "05:20", and you need to convert and store this data correctly. Any suggestions on how to achieve this? I've attempted using the Date object with ...

How to display an object in the template that does not have a specified property

I am dealing with an object that can have a type of WithBalance | WithoutBalance withBalance : { balance:number, name:string } withoutBalance : { name : string} <span>{{object?.balance ?? 0}} </span> However, when I attempt to access the bal ...

Guide to adding annotations to a PDF document using Angular 2

As a novice in the field of Angular development, I am seeking guidance. Currently, I have an application that displays PDF files. My goal is to be able to annotate and make changes on these PDF files by adding drawings such as circles, lines, or text. Ho ...

Building a Next.js application that supports both Javascript and Typescript

I currently have a Next.js app that is written in Javascript, but I am looking to transition to writing new code in Typescript. To add Typescript to my project, I tried creating a tsconfig.json file at the project root and then ran npm install --save-dev ...

Issue encountered while retrieving the response, in case the node.js server sends the response with a delay

My aim is to upload an image and have the nodeJS server send the path of that image folder back as a response. Unfortunately, when I try sending the response after completing a task, nothing seems to be happening on the angular-side. Below is my componen ...

What is the process for creating a Deep Copy of an object in Angular?

I have a specific entity class defined as follows: export class Contact { id: number; firstName: string; lastName: string; constructor(id?, firstName?, lastName?) { this.id = id; this.firstName = firstName; this.lastName = lastName; ...

Exploring the power of Angular's ViewChildren to iterate through QueryList items

My ngFor loop includes child components: @ViewChildren(SingleMultiSelectionComponent) singleMultiSelections: QueryList<SingleMultiSelectionComponent>; I am attempting to iterate through this QueryList: console.log(this.singleMultiSelections); // 1 i ...