beginnercoder
beginnercoder

Reputation: 81

angular click table header to sort rows

I am new to angular js, and honestly, I only know what I have been told by former colleague about the project that he passed on to me.

I am using forkJoin to get the data from database because I need to use two different sets of data to create one table on the web. AND there are other data tables that I need to call on that same web page. So, forkJoin was what my colleague recommended, and using ngOnInit() was messy as not all of data arrive at the same time.

From (AngularJS sorting rows by table header) I found about using $scope and angular.module in *.ts file and orderBy and ng-repeat in *.html file. I was trying to get that working, but it seems that this example is using hardcoded table, not calling data from database. Also, when using ng-repeat, the following code does not seem to recognize ng-repeat.

<tr ng-repeat="data in myTable|orderBy:'index':false">
   <ng-container *ngIf="someConditions">
      <td>{{ data.index }}</td> //data not recognized
   </ng-container>
</tr>

Second alternative that I found was use Sort by importing from @angular/material. But, when I was trying to deploy that code, it gave me an error, which seemed related to version of dependencies. To make my colleague's code work, he and I had to check versions of major dependencies and now all of them are in sync. So, I did not want to mess with version issues.

Finally, I found a way to sort table once when it is loaded on the web, but that is not exactly what I wanted to do. I want that table to dynamically sort rows whenever and whichever header I click. And that post (or answerer) said that ordering pipes should not be used. (Orderby with *ngFor array)

So,

  1. is there any way to implement header click sorter while using forkJoin and ngFor (which I can get it to work unlike ng-repeat)?

  2. If it is much better to use angular.module and $scope, then how can I use them while calling all the tables simultaneously (i.e. how can I integrate

var app = angular.module('app',[]);

app.controller('myCtrl', function($scope) {
   $scope.orderBy = 'index';
   ...
   $scope.data = {
      myData: [{
         ...
      }]
   };
});

into *.ts file?)

Upvotes: 1

Views: 1460

Answers (1)

SalunkeAkash
SalunkeAkash

Reputation: 256

try using this

<tr ng:repeat="row in body.$orderBy(sort.column, sort.descending)">
    <td>{{row.a}}</td>
    <td>{{row.b}}</td>
    <td>{{row.c}}</td>
</tr>

scope.sort = {
    column: 'b',
    descending: false
};

scope.selectedCls = function(column) {
    return column == scope.sort.column && 'sort-' + scope.sort.descending;
};

scope.changeSorting = function(column) {
    var sort = scope.sort;
    if (sort.column == column) {
        sort.descending = !sort.descending;
    } else {
        sort.column = column;
        sort.descending = false;
    }
};

Upvotes: 0

Related Questions