What is the best way to switch the direction of the arrows based on the sorting order?

Is there a way to dynamically change the direction of arrows based on sorting, similar to the example shown here?

sortingPipe.ts:

import { SprBitType } from '../spr-bit-type/sprBitType'; 
import { Pipe, PipeTransform } from '@angular/core'; 

@Pipe({
  name: 'sortingSprBitType'
})

export class SortingSprBitTypePipe implements PipeTransform {
  transform(sprBitTypes: SprBitType[], path: string[], order: number = 1): SprBitType[] {
    // Make sure parameters are not null before proceeding
    if (!sprBitTypes || !path || !order) return sprBitTypes;
    return sprBitTypes.sort((a: SprBitType, b: SprBitType) => {
      // Access each property based on the given path
      path.forEach(property => {
        a = a[property];
        b = b[property];
      });
      // Adjust the order based on specified criteria
      return a > b ? order : order * (-1);
    });
  }
}

sortingPipe.spec.ts:

import { TestBed, async } from '@angular/core/testing';
import { SortingSprBitTypePipe } from './sortingSprBitType.pipe';

describe('SortingSprBitTypePipe', () => {
  it('should create an instance', () => {
    const pipe = new SortingSprBitTypePipe();
    expect(pipe).toBeTruthy();
  });
});

Component.ts:

...
  path: string[] = ['sprBitType'];
  order: number = 1; // 1 for ascending, -1 for descending;

...

  sortTable(prop: string) {
    this.path = prop.split('.');
    this.order = this.order * (-1); // toggle order
    return false; // prevent reloading
  }

...

To display arrow symbols indicating the sorting direction (▲ ▼), HTML can be updated as follows:

<a class="sorting" (click)="sortTable('name')" >Name⬍</a>
<a class="sorting" (click)="sortTable('rn')"> RN⬍</a>

Answer №1

To achieve this functionality, you can utilize the Angular directive *ngIF based on the constant order.

Your HTML structure will be as follows:

<a class="sorting" (click)="sortTable('name')" >
    Name
    <label *ngIf="orderByName === 1">▲</label>
    <label *ngIf="orderByName === -1">▼</label>
</a>
<a class="sorting" (click)="sortTable('rn')"> 
    RN
    <label *ngIf="orderByRn === 1">▲</label>
    <label *ngIf="orderByRn === -1">▼</label>
</a>

In your Component.ts file, include the following code:

...

path: string[] = ['sprBitType'];
order: number = 1; // 1 for ascending, -1 for descending
orderByName: 1; // Assuming ascending is the default order for name
orderByRn: 1 // Assuming ascending is the default order for RN

...

sortTable(prop: string) {
    this.path = prop.split('.')
    this.order = this.order * (-1); // toggle order
    if(prop == name){
        this.orderByName = this.order;
    }
    if(prop == rn){
        this.orderByName = this.order;
    }
    return false; // prevent page reload
}

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

section element is not receiving styles from the specified class

Whenever I want to ensure that a class is only used on specific elements, I usually prefix it with the element name. For example, using div.className limits the className styling to just div elements. However, when I tried the same approach with a section ...

The styles in the CSS file are not behaving as expected

Having an issue with my CSS file for the Header.js module. Despite writing rules, only one style is applying. Can anyone help me identify the problem? Thanks in advance! Header.js component import React from 'react'; import '../../../asset/ ...

Creating an XPath expression for selecting multiple siblings of a div tag

Currently, I am working on writing an XPath expression for a specific section of code: <div class="line info"> <div class="unit labelInfo TextMdB">First</div> <div class="unit lastUnit"> <div clas ...

Tips for concealing information within the column labeled company Name with respect to the field designated as Company Name

I am currently working on an Angular 7 app and I am facing an issue: I cannot hide the data in the column for Company Name. The field "Name" in the report control JSON is labeled as Company Name. The report control is a table that contains various fields ...

issue with border color staying the same when focusing

I've been struggling with changing the border on focus in my code. Despite trying various methods, nothing seems to be working. Can someone help me figure out what I'm doing wrong? <input type="text" spellcheck="false" data-placement="top" id ...

The use of p-message in Angular's PrimeNg library is not permitted

Hey there, I'm having a bit of trouble with the p-message Tag in Angular. I believe I've imported it correctly as shown below. import { MessageModule } from 'primeng/message'; imports: [ .... MessageModule, ... In the ...

I am trying to verify my code, but the messages are not displaying under the username. They only appear under the password field. I am not sure where I have made a mistake

Having trouble with my login form validation using jQuery. Can someone help me fix it? $(document).ready(function() { $("#form1").validate({ rules: { username: { required: true, minlength: 6 }, password: { ...

What is the method for importing the "numeric" library version "^1.2.6" into an Angular project?

I recently added the package "numeric": "^1.2.6" to my project. In addition, I included the types: "@types/numeric": "^1.2.1" When attempting to import this into my Angular application: import * as numeric from &ap ...

Can you explain the significance of using `!important` in CSS without specifying a value?

Scenario: Currently, I am facing an issue with using the bootstrap 4 stylesheet in conjunction with NextJS. The bootstrap 4 stylesheet, compiled from SASS, contains code like: .checkbox.checkbox-accent > span { border-width: !important; } This speci ...

How can you implement a null filter in the mergeMap function below?

I created a subscription service to fetch a value, which was then used to call another API. However, the initial subscription API has now changed and the value can potentially be null. How should I handle this situation? My code is generating a compile e ...

The functionality of the Angular application is not compatible with Edge browser

Encountering an issue with loading my dashboard on Edge (works fine on Chrome). The page fails to load, unlike in Chrome. The problem seems to be linked to the code snippet ColorScale.js.pre-build-optimizer.js: /** * Set up color sca ...

Develop an Innovative Data-Driven Application using AJAX Technology

After inputting an artist's name and clicking on the button, I expect to receive a visually appealing list of their songs. I am encountering the following issue: Whenever I hit the button, no results are being returned, and I am unsure of the reaso ...

Generating an HTML table from SQL data using PHP

I'm attempting to create a dynamic HTML table using PHP to populate it with data from a MySQL database. I've tried using a while loop, but the issue is that it ends up displaying the same first row multiple times. <div class = "container"> ...

Error occurring with the gulp task runner

Encountering an error while using the task runner for my "gulp" file. My project involves Angular 2 and Asp.net Core. The "typings" folder is set up with a "typings.json" file that contains the following: { "resolution": "main", "tree": { "src": ...

A guide on obtaining the date format according to locale using Intl.DateTimeFormat within JavaScript

Can someone assist me in obtaining the standard date format (such as MM/DD/YYYY) based on a specified local id? The code snippet provided below is not returning the desired format. Any guidance on how to achieve this would be greatly appreciated. var da ...

Colored stripe on a horizontal menu

I am attempting to design a page header with a menu that resembles the image provided below. https://i.sstatic.net/623eH.png As I construct the navigation, each link area (highlighted in blue) is represented by an <li>. However, I am encountering a ...

The challenge of incorporating multiple stylesheets into an express/node/ejs application: encountering the error "Undefined style."

I am working on a project using express, node, and ejs and I want to be able to use different stylesheets for different views. In order to render a specific view with its corresponding style, I have included the following in my app.js file: app.get('/ ...

Can [] be considered a valid type in Typescript language?

I've come across this function: function stringToArray(s: string|[]): [] { return typeof s === 'string' ? JSON.parse(s.replace(/'/g, '"')) : s; } This function is functioning as expected without any type warnings. Bu ...

Is it possible to safely remove a class instance containing a GLcontext within a react.FC State to prevent memory leaks, especially when using a "class object with THREE.js"?

I have successfully developed a react.FC() application. In this application, you have the ability to throw a bottle in the metaverse (like a message in a bottle) to be discovered in the future. The app retrieves information from an API and constructs a c ...

Firebug displays CSS rule as blank

When I look at the styles in Firebug, I notice that the rule below has no content: .holest-carousel-top-item { box-shadow: 1px 1px 1px #FFF,-1px -1px 1px #9ACC67;border-radius: 85px; } Additionally, this rule is not displaying correctly in Firefox. ...