简体   繁体   中英

Apply class on div onclick and toggle class but initially don't set any class and remove class if clicked on other div in Angular / Typescript

I am working on an Angular app where I am showing data in table. Now when I click on any column of data it is sorting data in ascending and descending order.

Now what I want is when I initially load class it should not set any class but when I click on column (td) I want to display a down arrow (for descending order) up arrow(for ascending order). Also when I click on other column current column should remove class which I had set.

But when I load by default down arrow is there on all columns where I only want to set classes on particular td when I click on it and it should get removed if i click on some other class.

Reference link of how actually it should work here reference demo link

Here is 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 help will be great.

I don't know of it suits your needs, but since you are using Angular, you could check out Angular Material. There is a Table component which does exactly what you need and it is pretty easy u to set up.

Here's a link to the documentation: https://material.angular.io/components/table/overview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM