SoftEngi
SoftEngi

Reputation: 417

Build table with inconsistent column data

I need to build HTML table using angular on a data which has inconsistent number of columns cell in different rows. I need to display shaded cells for columns having lesser number of columns in any particular row. For example -

Data:

a,b,c,d
1,2,3
4,5,6,7
8,9,10,11,12

Expected output: expected output

Can this behavior be achieved using ng-repeat or some other way?

Upvotes: 0

Views: 187

Answers (1)

31piy
31piy

Reputation: 23859

You can find the largest collection of items, and then loop over it to create tds. Following is a working example, read the code comments to understand its working:

angular.module('app', [])
  .controller('ctrl', function($scope) {
    // The original data
    let data = 'a,b,c,d\n1,2,3\n4,5,6,7\n8,9,10,11,12';

    // Create arrays out of the original data. This will be used to render the table
    $scope.data = data.split('\n')
      .map(item => item.split(','));

    // Find the maximum number of elements so that we can create that much td elements
    $scope.max = Math.max(...$scope.data.map(item => item.length));

    // Helper function to create an array out of given length
    $scope.getArray = length => new Array(length);
  });
td {
  border: 1px solid black;
  width: 50px;
}

.blank {
  background-color: lightgray;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
  <table>
    <!--Loop over the rows of data-->
    <tr ng-repeat="row in data">
      <!--Loop over an empty array-->
      <td ng-repeat="_ in getArray(max) track by $index" ng-class="{blank: !row[$index]}">
        {{row[$index]}}
      </td>
    </tr>
  </table>
</div>

For graying out the unavailable items, it uses ng-class directive to assign a blank class to the td, which is then colored using CSS.

Upvotes: 1

Related Questions