Add a class to a div when clicked, then toggle the class. Start off with no class, and remove the class if another div is clicked in Angular/Typescript

I have been developing an Angular application that displays data in a table format. Currently, when I click on any column header, the data gets sorted in either ascending or descending order.

However, I want to implement a feature where initially no sorting classes are set on page load. Instead, when a column is clicked, a down arrow should indicate descending order and an up arrow for ascending order. Also, clicking on a different column should remove the sorting class from the previous one.

The issue I am facing is that by default, all columns have a down arrow displayed on page load, which is not the intended behavior. The sorting classes should only be applied when a specific column is clicked, and should be removed when another column is selected.

You can see a demonstration of the desired functionality here: reference demo link

Below is a snippet of my code:

data.html

<tr>
   <th (click)="sortAscending(sortedData)"  
   [ngClass]="status ? 'down-arrow' : 'up-arrow'">    State   </th>
   <th (click)="sortAscendingActive(sortedData)" 
   [ngClass]="status ? 'down-arrow' : 'up-arrow'">   Active Cases  </th>
   <th (click)="sortAscendingConfirmed(sortedData)" 
   [ngClass]="status ? 'down-arrow' : 'up-arrow'"> Confirmed Cases  </th>
   <th (click)="sortAscendingDeath(sortedData)"
   [ngClass]="status ? 'down-arrow' : 'up-arrow'">   Death  </th>
</tr>

data.ts

status =false

  sortByMaxCases(sortedDataBasedOnDate) {
    this.isAscendingSort = !this.isAscendingSort;
   this.status=true

    sortedDataBasedOnDate.forEach(item => item.statewise.sort(function (a, b) {
      if (b.confirmed < a.confirmed) {
        return -1;
      }
      if (b.confirmed > a.confirmed) {
        return 1;
      }
      return 0;
    }))
    this.calculateDiff(this.sortedDataBasedOnDate)

    if (!this.isAscendingSort) {
     this.status=!this.status
      sortedDataBasedOnDate.forEach(item => item.statewise.sort(function (a, b) {
        if (a.confirmed < b.confirmed) {
          return -1;
        }
        if (a.confirmed > b.confirmed) {
          return 1;
        }
        return 0;
      }))

      this.calculateDiff(this.sortedDataBasedOnDate)
    }
  }


Any assistance with this issue would be greatly appreciated.

Answer №1

If you're working with Angular, have you considered checking out Angular Material? They have a Table component that could be exactly what you're looking for and it's really simple to set up.

For more information, here's a link to the official documentation: https://material.angular.io/components/table/overview

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

What's the trick to aligning the label on the material-ui text field to the right side?

I am working on a React project with an RTL layout using material-ui and typescript. I am struggling to align the label of a text field to the right. Can anyone help me with this? https://i.sstatic.net/UrkIF.jpg ...

Is there an easy method to verify if the local storage is devoid of any data?

Query is named aptly; seeking to verify in a conditional statement. ...

Tips for retrieving information from a Vuetify modal window

Is it possible to retrieve data from a dialog in the VueJS Vuetify framework? Specifically, how can I access the username or password entered in the NewUserPopup.vue dialog from app.vue? App.vue = main template NewUserPopup.vue = Dialog template imported ...

Struggling with the transition of a CSS navigation menu from hover to focus

I'm attempting to transition a "mega menu" from 'hover' to 'focus'. My goal is to have the dropdown menus appear "on click" and remain visible until another top-level selection is clicked. Ideally, I am looking for a CSS-only solut ...

The object in three.js disappears from the scene but remains visible

I am attempting to showcase text as a sprite in three.js and aim to move the sprite along with an object. I achieve this by utilizing a canvas to generate a texture, which is then mapped using SpriteMaterial to create a sprite from it. However, when I remo ...

Is the form always being processed by onsubmit and confirm?

Apologies if this question has been asked before. I am currently working on a form where I ask the user to confirm an action, but it's not functioning as expected. The form proceeds regardless of whether the user clicks ok, cancel, or even closes the ...

Can an interface be expanded within an object array using React and Typescript?

I am working with two different interfaces: Interface 1: interface ILineItemProps { state: 'OPENED' | 'COMPLETED' | 'CANCELLED' | 'PENDING'; } Interface 2: interface IProps { steps: [ { ...

Two paths in AngularJS

In the AngularJS application, the ui-router is used to manage two types of pages: Pages with routes explicitly specified in routes.js Pages with routes dynamically derived on demand Upon loading the page, the application sends a request for data (type, ...

...additional properties in React function components using TypeScript

Here is a snippet of code that I am working with: <InputComponent id="email" name={formik.values.email} type="text" formik={formik} className="signInInput" disabled/> However, there seems to be an issue with the disable ...

What issues could arise from utilizing PHP for generating variables within my CSS file?

One major limitation of CSS is the absence of variables. It would be beneficial to have the ability to use variables for controlling things like the location of imported CSS and color schemes within a design. An alternative solution could involve using a ...

Encountering Undefined Object Error in Angular Framework

I just completed an upgrade to Angular and encountered an issue with the error message 'object is possibly undefined'. I have tried multiple solutions after doing some research online, including using 'if' statements, null coalescing, i ...

Guide on submitting a form via Ajax on a mobile app

Looking for a way to submit the form located in components/com_users/views/login/tmpl/default_login.php using Ajax. <form action="<?php echo JRoute::_('index.php?option=com_users&task=user.login'); ?>" method="post"> <fie ...

What could be causing my inability to accurately guess people's ages?

My latest project involves developing a game where players have to guess names from images. Each game consists of 10 rounds, followed by a bonus round where participants must wager their points on guessing the age of the person in the image within a 2-year ...

The HTML form label offers a choice between two alternatives

My usual method of styling forms involves organizing elements like this: <label for="CompanyNameTextBox"> <span>Company</span> <input name="CompanyNameTextBox" type="text" id="CompanyNameTextBox" /> </label> This set ...

Issue with TypeScript while trying to define a property of a named function expression using 'let' instead of 'const'

As I continued my journey through the TypeScript handbook, I stumbled upon an intriguing concept while learning about Call Signatures. The code snippet provided in the handbook goes like this: type DescribableFunction = { description: string; (someArg: n ...

The DefaultTheme in MaterialUI no longer recognizes the 'palette' property after transitioning from v4 to v5, causing it to stop functioning correctly

Currently in the process of transitioning my app from Material UI v4 to v5 and encountering a few challenges. One issue I'm facing is that the 'palette' property is not recognized by DefaultTheme from Material UI when used in makeStyles. Thi ...

implement some level of control within the ngFor directive in Angular

For instance, let's say I have an ngfor loop: <ng-container *ngFor="let setting of settings | trackBy: trackById"> <button mat-button [matMenuTriggerFor]="menu">Menu</button> <mat-me ...

What are the steps for distributing a styled React component?

My goal is to release a UI library using React, but I am struggling with how to handle styles. When I write code in a project, I typically use webpack and babel to build my code, resulting in the creation of a *.css file. import React from 'react&ap ...

Incorporate a new item into an array within a JSON `document` using Node.js for every incoming request

I'm facing an issue with storing multiple sets of x, y coordinates in a file on the server side. Currently, when a user right clicks on an image on the frontend, the coordinates are sent to the node server via AJAX post request and saved as objects in ...

How can I apply bold styling to my interpolation binding in Angular while working on my HTML code?

Below is the code snippet where I am attempting to highlight profile.userId: <p class="profile__last-login" *ngIf="profile.lastLoggedIn"> {{'intranet.profile.dashboard.lastLoggedIn' | messageBundle: profile.userId + ',' + (pr ...