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

The data type 'boolean' cannot be assigned to the type 'CaseReducer<ReportedCasesState, { payload: any; type: string; }>'

I recently developed a deletion reducer using reduxjs/toolkit: import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { AppThunk } from "../store"; import { ReportedCase, deleteReportCase } from "../../api/reportedCasesApi"; import history ...

Building a MEAN stack application using Angular 5 and implementing passportJS for authentication

What's the process for implementing authentication in a MEAN stack using Angular 5, Node.js, and Passport.js? ...

Add a npm module without type definitions

I am currently utilizing Typescript version 2.1 and facing an issue with installing an npm package called 'reactable' that lacks typings. When attempting to import the package using import * as Reactable from 'reactable', Typescript di ...

Adding a URL link to a mentioned user from angular2-mentions within an Angular 4 application can be achieved in the following way:

Need help with adding a URL RouterLink to mention a user using angular2-mentions. This is the code snippet I currently have: <div class="col-sm-12"> <input type="text" [mention]="contactNames" [mentionConfig]="{triggerChar:'@',maxI ...

A guide on implementing directives in Angular 2

I am trying to load my navbar.html in my app.component.html by using directives and following the method below: Here is my navbar html: <p>Hi, I am a pen</p> This is my navbar.ts: import {Component, Directive, OnInit} from '@angular/c ...

What is the best way to define a function agreement in Typescript?

I have created a function that can return `undefined` only when its argument is also `undefined`, otherwise it will always return a value derived from the argument provided. Here's an example of how the function works: function triple(value?: number) ...

State in Angular stubbornly refuses to switch despite condition changes

Here is the Typescript code, followed by the HTML: public verifySelection() { let choice = false; if (typeof this.formUser.permissionsTemplateID === undefined) { choice = true; } return choice; } <div class="form-group" ...

Attempting to implement endless scrolling functionality using rxjs and angular 2 framework

I'm struggling to understand how I can incorporate stream data into my infinite scroll feature. First, I define my observable variable and page offset: products$; offset: number = 0; Next, I create an observable using one of my services: this.prod ...

Encountering an Issue: The formGroup function requires an instance of a FormGroup. Kindly provide one

I am a beginner with Angular 2 and despite reviewing numerous stack overflow answers, I still can't resolve my issue. I have recently started learning about angular reactive forms and wanted to try out my first example but I'm facing some diffic ...

The Angular 2 quickstart guide seems to have gone missing following the latest 2

Quickstart Search Struggle I've hit a roadblock in my quest to locate the original Angular2 Quickstart, complete with package.json, tsconfig.ts, and systemjs.config.js files that are commonly referenced in online tutorials and youtube videos. Rumors ...

What is the process for sending data to the backend using an HTTP POST request? The frontend is built with Angular 2 and the backend is developed with .NET

Having trouble with this error message: Error: XMLHttpRequest cannot load "http://localhost:49873/api/home". The response to the preflight request failed the access control check. There is no 'Access-Control-Allow-Origin' header present on the ...

Error: Unable to locate script.exe when spawning the Nodejs process

When trying to run an exe in my electron app, I am encountering an error. Even though the path is correct, it still throws an error. Uncaught Error: spawn exe/0c8c86d42f4a8d77842972cdde6eb634.exe ENOENT at Process.ChildProcess._handle.onexit (inter ...

Elevate your AngularJS directive by incorporating ngModel into an Angular component

Attempting to switch my AngularJS directive over to an Angular Component. Below is the original code for the directive: ng1AppModule.component('ng1Tmp', { bindings: {p: '<'}, require: {ngModel: 'ngModel'} }); Her ...

Implementing a video pause event trigger from a function in Angular2

Here is the content of my player.component.html: <video width="320" height="240" autoplay autobuffer [src]="videoSrc" (ended)="videoEnd()"> Your browser does not support the video tag. </video> <button (click)="pauseOrPlay()">pause/play ...

What is the best way to extract data from Azure Data Lake and showcase it within an Angular-2 interface?

I am facing a challenge where I need to retrieve files with content from Azure Data Lake and display them in an Angular-2 Component. The issue is that when using the List File Status() method, I am only able to obtain file properties, not the actual conten ...

Access to Angular CORS request has been blocked

I'm currently working on establishing a connection between my Angular application and a basic REST server using express. The server responds to requests with JSON data exclusively. To enable CORS support, I've integrated the cors module from npm ...

Calculating the time difference between two dates in the format yyyy-MM-ddTHH:mm:ss.fffffff can be done by following these steps

Can someone help me figure out how to calculate the difference in days between the date and time 2021-02-23T08:31:37.1410141 (in the format yyyy-MM-ddTHH:mm:ss.fffffff) obtained from a server as a string, and the current date-time in an Angular application ...

The Angular Serviceworker does not store the index.html file in its cache

When my app goes offline, it doesn't work properly due to the angular serviceworker failing to cache my index.html file (although it does cache other files like js, css, manifest, and ico). The issue only occurs when the outputPath is within my git/nx ...

Using TypeScript to pass a callback function to labelFormatter in the legend of a Highcharts chart

I am currently experimenting with integrating HighCharts into an Angular2 project using TypeScript. My goal is to customize the appearance of the legend text, adding an image next to it. I've found that HighCharts provides a labelFormatter property w ...

Tips for correctly configuring child routing in Angular

I'm facing an issue with setting up child paths where the navigation path is incorrect Currently, I have a cabinet module with the following routers: const routes: Routes = [ { path: '', component: CabinetComponent, children: ...