FlexGrid 101

Getting Started

Steps for getting started with FlexGrid in AngularJS applications:

  1. Add references to AngularJS, Wijmo, and Wijmo's AngularJS directives.
  2. Include the Wijmo 5 directives in the app module:
    var app = angular.module('app', ['wj']);
  3. Add a controller to provide data and logic.
  4. Add a FlexGrid to the page and bind it to the data.
  5. Add some CSS to customize the grid's appearance.

This will create a FlexGrid with default behavior, which includes automatic column generation, column sorting and reordering, editing, and clipboard support.

<html> <head> <link rel="stylesheet" href="css/bootstrap.css"/> <link rel="stylesheet" href="css/wijmo.css" /> <link href="css/app.css" rel="stylesheet" /> <script src="scripts/angular.js"></script> <script src="scripts/wijmo.js"></script> <script src="scripts/wijmo.grid.js"></script> <script src="scripts/wijmo.angular.js"></script> <script src="scripts/app.js"></script> </head> <body ng-app="app" ng-controller="appCtrl"> <!-- this is the grid --> <wj-flex-grid items-source="data"> </wj-flex-grid> </body> </html>
// declare app module var app = angular.module('app', ['wj']); // app controller provides data app.controller('appCtrl', function appCtrl($scope) { // generate some random data var countries = 'US,Germany,UK,Japan,Italy,Greece'.split(','), data = []; for (var i = 0; i < 100; i++) { data.push({ id: i, country: countries[i % countries.length], date: new Date(2014, i % 12, i % 28), amount: Math.random() * 10000, active: i % 4 == 0 }); } // add data array to scope $scope.data = data; });
/* set default grid style */ .wj-flexgrid { height: 300px; background-color: white; box-shadow: 4px 4px 10px 0px rgba(50, 50, 50, 0.75); margin-bottom: 12px; }

Result (live):

Column Definitions

The Getting Started example did not define any columns, so FlexGrid generated them automatically.

This example shows how you can define the columns using HTML markup. You can also do this in code, but using markup allows you to have more separation between the controller and the view.

Specifying the columns allows you to choose which columns to show, and in what order. This also gives you control over each column's width, heading, formatting, alignment, and other properties.

In this case, we use star sizing to set the width of the "Country" column. This tells the column to stretch to fill the available width of the grid so there is no empty space. On the "Revenue" column, we set the format property to "n0", which results in numbers with thousand separators and no decimal digits.

<wj-flex-grid items-source="data"> <wj-flex-grid-column header="Country" binding="country" width="*"> </wj-flex-grid-column> <wj-flex-grid-column header="Date" binding="date"> </wj-flex-grid-column> <wj-flex-grid-column header="Revenue" binding="amount" format="n0" > </wj-flex-grid-column> <wj-flex-grid-column header="Active" binding="active"> </wj-flex-grid-column> </wj-flex-grid>

Result (live):

Selection Modes

By default, FlexGrid allows you to select a range of cells with the mouse or keyboard, just like Excel. The selectionMode property allows you to change that so that you can select a row, a range of rows, non-contiguous rows (like in a list-box), a single cell, or disable selection altogether.

This example allows you to pick the selectionMode from a Wijmo Menu control.

<wj-flex-grid items-source="data" selection-mode="{​{selectionMode}}"> </wj-flex-grid> <wj-menu value="selectionMode" header="Selection Mode" > <wj-menu-item value="'None'">None</wj-menu-item> <wj-menu-item value="'Cell'">Cell</wj-menu-item> <wj-menu-item value="'CellRange'">CellRange</wj-menu-item> <wj-menu-item value="'Row'">Row</wj-menu-item> <wj-menu-item value="'RowRange'">RowRange</wj-menu-item> <wj-menu-item value="'ListBox'">ListBox</wj-menu-item> </wj-menu>
// initialize selection mode $scope.selectionMode = 'CellRange';

Result (live):

None Cell CellRange Row RowRange ListBox

Cell Freezing

The FlexGrid allows you to freeze rows and columns so they remain in view as the user scrolls the grid. Frozen cells can be edited and selected as regular cells, exactly as in Excel.

This example allows you to toggle whether the first two rows and columns should be frozen.

<wj-flex-grid control="frozenFlex" items-source="data" frozen-rows="2" frozen-columns="2"> </wj-flex-grid> <button class="btn btn-default" ng-click="toggleFreeze()"> {​{ frozenFlex.frozenRows == 0 ? 'Freeze' : 'Unfreeze'}} </button>
// toggle frozen rows/columns $scope.toggleFreeze = function () { var flex = $scope.frozenFlex; if (flex) { var frozenCount = flex.frozenRows == 0 ? 2 : 0; flex.frozenRows = frozenCount; flex.frozenColumns = frozenCount; } }
/* frozen cells */ .wj-frozen:not(.wj-state-selected):not(.wj-state-multi-selected) { background-color: #f8ffd6; } .wj-frozen.wj-alt:not(.wj-state-selected):not(.wj-state-multi-selected) { background-color: #f8ffd6; } /* frozen area edges */ .wj-frozen-row { border-bottom: 1px solid rgba(0,0,0,.5); } .wj-frozen-col { border-right: 1px solid rgba(0,0,0,.5); }

Result (live):

Editing

FlexGrid has built-in support for fast, in-cell editing like you find in Excel. There is no need to add extra columns with Edit buttons that switch between display and edit modes.

Users can start editing by typing into any cell. This puts the cell in quick-edit mode. In this mode, pressing a cursor key finishes the editing and moves the selection to a different cell.

Another way to start editing is by pressing F2 or by clicking a cell twice. This puts the cell in full-edit mode. In this mode, pressing a cursor key moves the caret within the cell text. To finish editing and move to another cell, the user must press the Enter, Tab, or Escape key.

Data is automatically coerced to the proper type when editing finishes. If the user enters invalid data, the edit is cancelled and the original data remains in place.

You can disable editing at the grid, column, or row levels using the isReadOnly property of the grid, column, or row objects. In this example, we make the ID column read-only.

<wj-flex-grid items-source="data"> <wj-flex-grid-column header="ID" binding="id" is-read-only="true"> </wj-flex-grid-column> <wj-flex-grid-column header="Country" binding="country" width="*"> </wj-flex-grid-column> <wj-flex-grid-column header="Date" binding="date"> </wj-flex-grid-column> <wj-flex-grid-column header="Revenue" binding="amount" format="n0" > </wj-flex-grid-column> <wj-flex-grid-column header="Active" binding="active"> </wj-flex-grid-column> </wj-flex-grid>

Result (live):

Grouping

FlexGrid supports grouping through the ICollectionView interface, which is identical to the one in .NET. To enable grouping, add one or more GroupDescription objects to the CollectionView.groupDescriptions property, and ensure that the grid's showGroups property is set to true (the default value).

GroupDescription objects are flexible, allowing you to group data based on value or on grouping functions. The example below groups dates by year; amounts by range returning three ranges: over 5,000, 500 to 5,000, and under 500; and anything else by value. Use the menu to see the effects of each grouping.

Notice that the "Revenue" column displays the totals in the group rows. We do this by setting the column's aggregate property to "Sum." The aggregate is automatically updated when you edit the values in the column.

<wj-flex-grid items-source="cvGroup"> <wj-flex-grid-column header="Country" binding="country" width="*"> </wj-flex-grid-column> <wj-flex-grid-column header="Date" binding="date"> </wj-flex-grid-column> <wj-flex-grid-column header="Revenue" binding="amount" format="n0" aggregate="Sum"> </wj-flex-grid-column> </wj-flex-grid> <wj-menu value="groupBy" header="Group by" > <wj-menu-item value="''">(no grouping)</wj-menu-item> <wj-menu-item value="'country'">Country</wj-menu-item> <wj-menu-item value="'amount'">Revenue</wj-menu-item> <wj-menu-item value="'date'">Date</wj-menu-item> <wj-menu-item value="'country,date'">Country and Date</wj-menu-item> <wj-menu-item value="'country,amount'">Country and Revenue</wj-menu-item> <wj-menu-item value="'country,date,amount'">Country, Date, and Revenue</wj-menu-item> </wj-menu>
// expose the data as a CollectionView to show grouping $scope.cvGroup = new wijmo.collections.CollectionView(data); $scope.groupBy = ''; // update CollectionView group descriptions when groupBy changes $scope.$watch('groupBy', function () { var cv = $scope.cvGroup; cv.groupDescriptions.clear(); // clear current groups if ($scope.groupBy) { var groupNames = $scope.groupBy.split(','); for (var i = 0; i < groupNames.length; i++) { var groupName = groupNames[i]; if (groupName == 'date') { // ** group dates by year var groupDesc = new wijmo.collections.PropertyGroupDescription(groupName, function (item, prop) { return item.date.getFullYear(); }); cv.groupDescriptions.push(groupDesc); } else if (groupName == 'amount') { // ** group amounts in ranges var groupDesc = new wijmo.collections.PropertyGroupDescription(groupName, function (item, prop) { return item.amount >= 5000 ? '> 5,000' : item.amount >= 500 ? '500 to 5,000' : '< 500'; }); cv.groupDescriptions.push(groupDesc); } else { // ** group everything else by value var groupDesc = new wijmo.collections.PropertyGroupDescription(groupName); cv.groupDescriptions.push(groupDesc); } } } });

Result (live):

(no grouping) Country Revenue Date Country and Date Country and Revenue Country, Date, and Revenue

Filtering

The FlexGrid supports filtering through the ICollectionView interface, which is identical to the one in .NET. To enable filtering, set the CollectionView.filter property to a function that determines which objects to include in the view.

In this example, we create a filter for the country, and get the filter value from the input control.

<wj-flex-grid items-source="cvFilter"> </wj-flex-grid> <div class="input-group"> <span class="input-group-addon"> <span class="glyphicon glyphicon-filter"></span> </span> <input type="text" ng-model="filter" class="form-control" placeholder="filter"/> </div>
// expose the data as a CollectionView to show filtering $scope.filter = ''; var toFilter, lcFilter; $scope.cvFilter = new wijmo.collections.CollectionView(data); $scope.cvFilter.filter = function (item) { // ** filter function if (!$scope.filter) { return true; } return item.country.toLowerCase().indexOf(lcFilter) > -1; }; $scope.$watch('filter', function () { // ** refresh view when filter changes if (toFilter) { clearTimeout(toFilter); } toFilter = setTimeout(function () { lcFilter = $scope.filter.toLowerCase(); $scope.cvFilter.refresh(); }, 500); });

Result (live):

Paging

The FlexGrid supports paging through the IPagedCollectionView interface, which is nearly identical to the one in .NET. To enable paging, set the IPagedCollectionView.pageSize property to the number of items you want on each page, and provide a UI for navigating the pages.

In this example, we use JavaScript to show 10 items per page. We add navigation buttons, and call IPagedCollectionView methods in the button click directives. Note that we use the pageIndex and pageCount properties to show the current page and total number of pages.

<wj-flex-grid items-source="cvPaging" style="height:auto"> </wj-flex-grid> <div class="btn-group"> <button type="button" class="btn" ng-click="cvPaging.moveToFirstPage()"> <span class="glyphicon glyphicon-fast-backward"></span> </button> <button type="button" class="btn" ng-click="cvPaging.moveToPreviousPage()"> <span class="glyphicon glyphicon-step-backward"></span> </button> <button type="button" class="btn" disabled style="width:100px"> {​{cvPaging.pageIndex + 1 | number}} / {​{cvPaging.pageCount | number}} </button> <button type="button" class="btn" ng-click="cvPaging.moveToNextPage()"> <span class="glyphicon glyphicon-step-forward"></span> </button> <button type="button" class="btn" ng-click="cvPaging.moveToLastPage()"> <span class="glyphicon glyphicon-fast-forward"></span> </button> </div>
// expose the data as a CollectionView to show paging $scope.cvPaging = new wijmo.collections.CollectionView(data); $scope.cvPaging.pageSize = 10;

Result (live):

Master-Detail

The ICollectionView interface has built-in support for currency, which enables you to implement master-detail scenarios with FlexGrid. You can refer to the currentItem and use it as a binding source for any elements on the page.

Note that you have to tell AngularJS when the current item changes. To do that, attach a handler to the ICollectionView.currentChanged event and call $scope.$apply as shown in the JS tab of this sample.

<wj-flex-grid items-source="cvFilter" is-read-only="true"> <wj-flex-grid-column header="Country" binding="country" width="*"> </wj-flex-grid-column> <wj-flex-grid-column header="Date" binding="date"> </wj-flex-grid-column> </wj-flex-grid> <dl class="dl-horizontal"> <dt>ID</dt> <dd>{​{cvFilter.currentItem.id}}</dd> <dt>Country</dt> <dd>{​{cvFilter.currentItem.country}}</dd> <dt>Date</dt> <dd>{​{cvFilter.currentItem.date | date}}</dd> <dt>Revenue</dt> <dd>{​{cvFilter.currentItem.amount | number:2}}</dd> </dl>
// tell scope when current item changes $scope.cvFilter.currentChanged.addHandler(function () { $scope.$apply('cvFilter.currentItem'); });

Result (live):

ID
{{cvFilter.currentItem.id}}
Country
{{cvFilter.currentItem.country}}
Date
{{cvFilter.currentItem.date | date}}
Revenue
{{cvFilter.currentItem.amount | number:2}}

Cell Templates

FlexGrid has an itemFormatter property that gives you complete control over the contents of the cells. The AngularJS directive we provide for the grid uses this to support in-line cell templates, so you can define the appearance of the cells using plain HTML.

To define a cell template for a column, add the HTML to display in each cell to the column definition. Use the $item variable to access the data item from within the template.

<wj-flex-grid items-source="data"> <wj-flex-grid-column header="Country" binding="country" width="*" is-read-only="true"> <img ng-src="resources/{​{$item.country}}.png" /> {​{$item.country}} </wj-flex-grid-column> <wj-flex-grid-column header="Date" binding="date"> </wj-flex-grid-column> <wj-flex-grid-column header="Revenue" binding="amount" format="n0" > </wj-flex-grid-column> <wj-flex-grid-column header="Active" binding="active"> </wj-flex-grid-column> </wj-flex-grid>

Result (live):

{{$item.country}}

Conditional Styling

The wj-flex-flex-grid-column directive supports the ng-style directive. This allows you to customize the style used to display the data in each cell based on its value.

This example uses a JavaScript function to create value ranges that return named colors. We then call this function in the Revenue column inside the ng-style directive and use the $item variable to pass in the data and set the color.

<wj-flex-grid items-source="data"> <wj-flex-grid-column header="Country" binding="country" width="*"> </wj-flex-grid-column> <wj-flex-grid-column header="Date" binding="date"> </wj-flex-grid-column> <wj-flex-grid-column header="Revenue" binding="amount" format="n0" ng-style="{color:getAmountColor($item.amount)}"> </wj-flex-grid-column> <wj-flex-grid-column header="Active" binding="active"> </wj-flex-grid-column> </wj-flex-grid>
// get the color to use to display the amount $scope.getAmountColor = function (amount) { if (amount < 500) return 'darkred'; if (amount < 2500) return 'black'; return 'darkgreen'; }

Result (live):

Themes

The appearance of the FlexGrid is defined in CSS. In addition to the default theme, we include about a dozen professionally designed themes that customize the appearance of all Wijmo controls to achieve a consistent, attractive look.

You can customize the appearance of the grid using CSS. To do this, copy CSS rules from the default theme to a new CSS file and modify the style attributes you want to change.

In this example, we add a "custom-flex-grid" class to the grid element and define some CSS rules to create a simple "black and white, no borders" theme for any grids that have the "custom-flex-grid" class.

We also customize the appearance of the glyphs used to show the column sorting direction and the outline nodes in grouped grids. To see the custom glyphs, click a column header cell.

<wj-flex-grid items-source="data" class="custom-flex-grid"> </wj-flex-grid>
/* create a 'custom-flex-grid' theme for the FlexGrid */ .custom-flex-grid .wj-header.wj-cell { background-color: #000; color: #fff; font-weight: bold; border-right: solid 1px #404040; border-bottom: solid 1px #404040; } .custom-flex-grid .wj-cell { border: none; background-color: #fff; } .custom-flex-grid .wj-alt:not(.wj-state-selected):not(.wj-state-multi-selected) { background-color: #fff; } .custom-flex-grid .wj-state-selected { background: #000; color: #fff; } .custom-flex-grid .wj-state-multi-selected { background: #222222; color: #fff; } /* override the glyphs used to show sorting and grouping */ .custom-flex-grid .wj-glyph-up { background-image:url('../resources/ascending.png'); background-repeat: no-repeat; background-position: bottom right; width: 1em; height: 1em; border-top: 0px; border-bottom: 0px; border-left: 0px; border-right: 0px; opacity: 1; } .custom-flex-grid .wj-glyph-down { background-image:url('../resources/descending.png'); background-repeat: no-repeat; background-position: bottom right; width: 1em; height: 1em; border-top: 0px; border-bottom: 0px; border-left: 0px; border-right: 0px; opacity: 1; } .custom-flex-grid .wj-glyph-right { background-image:url('../resources/collapsed.png'); background-repeat: no-repeat; background-position: bottom right; width: 1em; height: 1em; border-top: 0px; border-bottom: 0px; border-left: 0px; border-right: 0px; } .custom-flex-grid .wj-glyph-down-right { background-image:url('../resources/expanded.png'); background-repeat: no-repeat; background-position: bottom right; width: 1em; height: 1em; border-top: 0px; border-bottom: 0px; border-left: 0px; border-right: 0px; }

Result (live):

Trees and Hierarchical Data

In addition to grouping, FlexGrid supports hierarchical data, that is, data with items that have lists of subitems. This type of hierarchical structure is very common, and is usually displayed in a tree-view control.

To use FlexGrid with hierarchical data sources, set the childItemsPath property to the name of the data element that contains the child elements. The grid automatically scans the data and builds the tree for you.

<wj-flex-grid class="custom-flex-grid" items-source="treeData" child-items-path="items" allow-resizing="None" selection-mode="ListBox" headers-visibility="None"> <wj-flex-grid-column binding="name" width="*"> </wj-flex-grid-column> <wj-flex-grid-column binding="length" width="80" align="center"> </wj-flex-grid-column> </wj-flex-grid>
// hierarchical data $scope.treeData = [ { name: '\u266B Adriane Simione', items: [ { name: '\u266A Intelligible Sky', items: [ { name: 'Theories', length: '2:02' }, { name: 'Giant Eyes', length: '3:29' }, { name: 'Jovian Moons', length: '1:02' }, { name: 'Open Minds', length: '2:41' }, { name: 'Spacetronic Eyes', length: '3:41' }] } ]}, { name: '\u266B Amy Winehouse', items: [ { name: '\u266A Back to Black', items: [ { name: 'Addicted', length: '1:34' }, { name: 'He Can Only Hold Her', length: '2:22' }, { name: 'Some Unholy War', length: '2:21' }, { name: 'Wake Up Alone', length: '3:43' }, { name: 'Tears Dry On Their Own', length: '1:25' }] }, // more hierarchical data...
/* override the glyphs used to show sorting and grouping */ .custom-flex-grid .wj-glyph-up { background-image:url('../resources/ascending.png'); background-repeat: no-repeat; background-position: bottom right; width: 1em; height: 1em; border-top: 0px; border-bottom: 0px; border-left: 0px; border-right: 0px; opacity: 1; } .custom-flex-grid .wj-glyph-down { background-image:url('../resources/descending.png'); background-repeat: no-repeat; background-position: bottom right; width: 1em; height: 1em; border-top: 0px; border-bottom: 0px; border-left: 0px; border-right: 0px; opacity: 1; } .custom-flex-grid .wj-glyph-right { background-image:url('../resources/collapsed.png'); background-repeat: no-repeat; background-position: bottom right; width: 1em; height: 1em; border-top: 0px; border-bottom: 0px; border-left: 0px; border-right: 0px; } .custom-flex-grid .wj-glyph-down-right { background-image:url('../resources/expanded.png'); background-repeat: no-repeat; background-position: bottom right; width: 1em; height: 1em; border-top: 0px; border-bottom: 0px; border-left: 0px; border-right: 0px; }

Result (live):

Sorting Trees

By default, sorting a grid containing hierarchical data only sorts the top-level items. This is because the CollectionView does not know about the data hierarchy, since the childItemsPath property belongs to the grid and not to the underlying CollectionView.

If you do want to sort some or all of the grid's child items, you should handle the grid's sortedColumn event to enumerate the items and perform the additional sorting on the child items yourself.

This example shows how to do this assuming you want the child items sorted in the same order as the top-level items. In this scenario, you can call the sort method on the child items array using the CollectionView's _compareItems method to compare the items. This is the same method the CollectionView uses internally.

<wj-flex-grid class="custom-flex-grid" items-source="treeData" child-items-path="items" selection-mode="ListBox" headers-visibility="Column" sorted-column="sortedColumn(s,e)"> <wj-flex-grid-column binding="name" width="*"></wj-flex-grid-column> <wj-flex-grid-column binding="length" width="80" align="center"></wj-flex-grid-column> </wj-flex-grid>
$scope.sortedColumn = function (s, e) { var view = s.collectionView; if (view && s.childItemsPath) { for (var i = 0; i < view.items.length; i++) { sortItem(view.items[i], view, s.childItemsPath); } view.refresh(); } } function sortItem(item, view, childItemsPath) { var children = item[childItemsPath]; if (children && wijmo.isArray(children)) { children.sort(view._compareItems()); for (var i = 0; i < children.length; i++) { sortItem(children[i], view, childItemsPath); } } }

Result (live):

Handling null values

By default, FlexGrid allows you to enter empty values in columns of type string, and will not allow empty/null values in columns of any other type.

You can change this behavior using the isRequired property on grid columns. If you set the isRequired property to false, the grid will allow you to enter empty values in that column, regardless of type. Conversely, if you set the isRequired property to true, the grid will not allow empty values even in string columns.

Setting isRequired to null reverts to the default behavior (nulls allowed only in string columns).

The grid below reverts the default behavior. It sets isRequired to true for the first column and to false for the others. You can delete content that is not required by entering an empty string or simply by pressing the delete key.

<wj-flex-grid items-source="data"> <wj-flex-grid-column header="Country" binding="country" width="*" is-required="true"> </wj-flex-grid-column> <wj-flex-grid-column header="Date" binding="date" is-required="false"> </wj-flex-grid-column> <wj-flex-grid-column header="Revenue" binding="amount" format="n0" is-required="false"> </wj-flex-grid-column> <wj-flex-grid-column header="Active" binding="active" is-required="false"> </wj-flex-grid-column> </wj-flex-grid>

Result (live):