Angular Material Grid

admin 11/23/2021
37 Comments
  1. Angular Material Grid Grouping
  2. Angular Material Grid List
  3. Angular Material Grid Paging
  4. Angular Material Grid Demo
  5. Angular Material Grid Table
  6. Angular Material Grid Examples
jQWidgets Angular Grid is an advanced data grid user interface component built on top of Typescript, Angular and the jQWidgets framework. It is feature complete and is built by the same developers who implemented the best Javascript Grid – jqxGrid. With our Angular Grid, you can use the same API and functionalities.

GREAT PERFORMANCE


The md-grid-list, an Angular directive, is a component for laying out content for varying screen sizes. A grid has 12 columns in the desktop size screen, 8 in the tablet size screen, and 4 in the phone size screen, where each size have predefined margins and gutters. Cells are laid out in sequential manner in a row, in the order they are defined.

jqxGrid offers fast data updates on all end-user features such as grouping, sorting, paging, and scrolling. The Angular Grid also comes with row and column virtualization, which minimizes the amount of items that need to be rendered, and ensures unbeatable performance in spread-like scenarios with thousands of rows and columns.
  • The Material Design layout grid can be customized for touch UIs that scroll horizontally. Columns, gutters, and margins are laid out from left to right, rather than top to bottom. The height of the screen determines the number of columns in a horizontal grid. Horizontally scrolling UIs are uncommon on non-touch and web platforms.
  • Angular Data Grid sample using Material Design styling Features enabled: sorting, filtering, sync with browser URLs, pagination and item-per-page functionality. Out-of-box Angular Material layout and input controls used, along with Material Design Light default CSS for grid styling.

UNIQUE FLEXIBILITY


jqxGrid is developed on top of the jQWidgets UI Framework and delivers a combination of unique features which can be easily enabled, disabled or customized. Our Angular Grid provides the ultimate flexibility over your data and its presentations including paging, grouping and sorting.

SORTING


The Angular Grid supports built-in powerful sorting capabilities like one-click automatic sorting, selection of sort option from a context menu, and sorting through APIs. The data grid automatically chooses the most appropriate comparison. Users can also implement and use a custom sort comparer. The sorting works well with all possible configurations including rows grouping and paging. Angular Grid also has an option to display an additional background in the sorted column.
Some of the other supported features by our Angular Grid are: Filtering, Paging, Grouping, Nested Grids, Pinned(Frozen) Columns, Conditional Formatting, Cells Editing, Row Editing, Data Validation and many more.
Lets start with a simple Angular Grid setup:
Template:
Component:
As you can see we can either directly assign value to the property like with the width or we can use a property from our component class – source & columns.
And here is the result:
Now let’s add some features to the Angular Grid:
The code in AppComponent stays the same(as above Component example), because we don’t have anything new we need from there.
Paging Feature:
jQWidgets Angular Grid has integrated paging functionality that lets the users to view large data sets in multiple pages for faster loading and intuitive navigation. Users also have an option to select how many records they would like to see on a page by using a page-size dropdown. To navigate to a page, users can enter the page number in the page-input box and click the ‘enter’ key or they can click the ‘next’ and ‘previous’ navigation buttons to navigate to the next or the previous page.
Filtering Feature:
Every event you have in the normal jqxGrid is available in Angular Grid too. All you need to do is write on before it and upperCase it’s first letter.
You bind it like this:
The Angular Grid by jQWidgets is fast and easy to use. It works across devices and has a consistent look and behavior on PCs, tablets and mobile phones. It is a perfect solution for complex Angular UI applications.
Browser our Grid demos: https://www.jqwidgets.com/angular/angular-grid/

The Ignite UI for Angular Data Grid is used to display and manipulate data with ease. Quickly bind your data with very little code or use a variety of events to customize different behaviors. This component provides a rich set of features like data selection, excel style filtering, sorting, paging, templating and column moving. Displaying tabular data has never been easier and beautiful thanks to the Material Table-based UI Grid.

Angular Data Grid Example

Boston Marathon 2020 – In this angular grid example, you can see how users can do both basic and excel-style filtering, live-data sorting, as well as using of grid summaries and cell templating that includes our Sparkline component, Circular Progress Indicator component, and Icons. The demo also includes custom paging and per page usage part of the Angular Pagination.

Getting Started with Ignite UI for Angular Data Grid

Dependencies

Note

This component requires HammerModule to be imported in the root module of the application in order for touch interactions to work as expected..

To get started with the Angular data grid, first you need to install Ignite UI for Angular by typing the following command:

For a complete introduction to the Ignite UI for Angular, read the getting started topic.

Angular Material Grid Grouping

The Angular grid is exported as an NgModule, thus all you need to do in your application is to import the IgxGridModule inside your AppModule:

Each of the components, directives and helper classes in the IgxGridModule can be imported either through the grid sub-package or through the main bundle in igniteui-angular. While you don't need to import all of them to instantiate and use the grid, you usually will import them (or your editor will auto-import them for you) when declaring types that are part of the grid API.

Usage

Now that we have the grid module imported, let’s get started with a basic configuration of the igx-grid that binds to local data:

The id property is a string value and is the unique identifier of the grid which will be autogenerated if not provided, while data binds the grid, in this case to local data.

The autoGenerate property tells the igx-grid to auto generate the grid's IgxColumnComponent based on the data source fields. It will also try to deduce the appropriate data type for the column if possible. Otherwise, the developer needs to explicitly define the columns and the mapping to the data source fields.

Angular Bootstrap Grid Definition

Angular Material Grid

Ignite UI for Angular includes a powerful bootstrap grid like flex-based layout system. Any modern application today is expected to follow a responsive web design approach, meaning it can gracefully adjust layout of HTML elements based on the device size, or from simply resizing the browser. An Angular bootstrap grid layout was the most used approach in the past, but a flex-based layout system like CSS grid has become more popular, as it works in any browser. The Ignite UI for Angular Layout Directive allows vertical and horizontal flow, including content / text wrapping, justification, and alignment. The Ignite UI for Angular grid supports a responsive layout using CSS, giving you the ultimate flexibility in how the grid behaves on resize.

Angular Grid Styling Configuration

Note

The IgxGridComponent uses css grid layout, which is not supported in IE without prefixing, consequently it will not render properly.

In Angular most of the styles are prefixed implicitly thanks to the Autoprefixer plugin.

For prefixing grid layouts however, you need to enable the Autoprefixergrid property with the comment /* autoprefixer grid:on */.

To facilitate your work, apply the comment in the src/styles.scss file.

Editable Grid Angular

Each operation for Angular grid editing includes Batch operations, meaning the API gives you the option to group edits into a single server call, or you can perform grid edit / update operations as they occur with grid interactions. Along with a great developer experience as an editable Angular grid with CRUD operations, the Angular grid includes Excel-like keyboard navigation. Common default grid navigation is included, plus the option to override any navigation option to meet the needs of your customers. An editable grid in Angular with a great navigation scheme is critical to any modern line of business application, with the Ignite UI grid we make it easy.

Following this topic you will learn more about cell template and cell editing template and editing.

Angular Grid Column Configuration

IgxColumnComponent is used to define the grid's columns collection and to enable features per column like sorting and paging. Cell, header, and footer templates are also available.

Defining Columns

Let's turn the autoGenerate property off and define the columns collection in the markup:

Each of the columns of the grid can be templated separately. The column expects ng-template Angular grid module directives.

Header Template

igxHeader targets the column header providing as a context the column object itself.

Note

Whenever a header template is used along with grouping/moving functionality the column header area becomes draggable and you cannot access the custom elements part of the header template until you mark them as not draggable. Example below.

As you can see, we are adding draggable attribute set to false.

Cell Template

igxCell applies the provided template to all cells in the column. The context object provided in the template consists of the cell value provided implicitly and the cell object itself. It can be used to define a template where the cells can grow according to their content, as in the below example.

In the snippet above we 'take' a reference to the implicitly provided cell value. This is sufficient if you just want to present some data and maybe apply some custom styling or pipe transforms over the value of the cell. However even more useful is to take the IgxGridCellComponent object itself as shown below:

When changing data through the cell template using ngModel, you need to call the appropriate API methods to make sure the value is correctly updated in the Angular grid's underlying data collection. In the snippet above, the ngModelChange call passes through the grid's editing API and goes through the grid's editing pipeline, properly triggering transactions(if applicable) and handling of summaries, selection, etc. However, this ngModelChange will fire every time the value of the cell changes, not just when the user is done editing, resulting in a lot more API calls.

Grid
Note

The grid exposes a default handling for number, string, date and boolean column types. For example, the column will display check or close icon, instead of true/false by default, for boolean column type.

If the data in a cell is bound with [(ngModel)] and the value change is not handled, the new value will not be properly updated in the Angular grid's underlying data source. When dealing with cell editing with a custom template, it is strongly advised to use the cell's cell editing template.

When properly implemented, the cell editing template also ensures that the cell's editValue will correctly pass through the grid editing event cycle.

Cell Editing Template

The column also accepts one last template that will be used when a cell is in edit mode. As with the other column templates, the provided context object is again the cell value and the cell object itself. Of course in order to make the edit-mode template accessible to end users, you need to set the editable property of the IgxColumnComponent to true.

Make sure to check the API for the IgxGridCellComponent in order to get accustomed with the provided properties you can use in your templates.

Column Template API

Each of the column templates can be changed programmatically at any point through the IgxColumnComponent object itself. For example in the code below, we have declared two templates for our user data. In our TypeScript code we'll get references to the templates themselves and then based on some condition we will render the appropriate template for the column in our application.

Column properties can also be set in code in the initColumns event which is emitted when the columns are initialized in the grid.

The code above will make the ProductName column sortable and editable and will instantiate the corresponding features UI (like inputs for editing, etc.).

Custom Display Format

All values for a date, numeric, currency and percent column are transformed through the Angular DatePipe, DecimalPipe, CurrencyPipe and PercentPipe accordingly. This does not modify the original value, just the value that is displayed in the column. So please keep in mind that all data operations and manipulations are done based on the values in your data source. By default, values will be displayed according to the grid locale (if not specified, it fallbacks to the application locale, which defaults to 'en-US').

See Setting up the locale of your app for more details.

Also, there are optional parameters for formatting:

  • format - determines what date/time parts are displayed, defaults to 'mediumDate', equivalent to 'MMM d, y'
  • timezone - the timezone offset for dates. By default uses the end-user's local system timezone
  • digitsInfo - decimal representation objects. Default to '1.0-3'

To allow customizing the display format by these parameters, the pipeArgs input is exposed. A column will respect only the corresponding properties for its data type, if pipeArgs is set. Example:

The OrderDate column will respect only the format and timezone properties, while the UnitPrice will only respect the digitsInfo. For further details, please check the official Angular documentation at Localizing your app.

All available column data types could be found in the official Column types topic.

Angular Grid Data Structure

The IgxGridComponent handles flat data and nested POJOs(Plain old Java objects). The data structure specific for rendering is in the form:

Warning

The key values must not contain arrays.

If you use autoGenerate columns the data keys must be identical.

Angular Grid Data Binding

Before going any further with the grid we want to change the Angular grid to bind to remote data service, which is the common scenario in large-scale applications. A good practice is to separate all data fetching related logic in a separate data service, so we are going to create a service which will handle the fetching of data from the server.

Let's implement our service in a separate file

We're importing the Injectable decorator which is an essential ingredient in every Angular service definition. The HttpClient will provide us with the functionality to communicate with backend services. It returns an Observable of some result to which we will subscribe in our grid component.

Note: Before Angular 5 the HttpClient was located in @angular/http and was named Http.

Since we will receive a JSON response containing an array of records, we may as well help ourselves by specifing what kind of data we're expecting to be returned in the observable by defining an interface with the correct shape. Type checking is always recommended and can save you some headaches down the road.

The service itself is pretty simple consisting of one method: fetchData that will return an Observable<NorthwindRecord[]>. In cases when the request fails for any reason (server unavailable, network error, etc), the HttpClient will return an error. We'll leverage the catchError operator which intercepts an Observable that failed and passes the error to an error handler. Our error handler will log the error and return a safe value.

Make sure to import both the HttpClientModule and our service in the application module and register the service as a provider.

After implementing the service we will inject it in our component's constructor and use it to retrieve the data. The ngOnInit lifecycle hook is a good place to dispatch the initial request.

Note: In the code below, you may wonder why are we setting the records property to an empty array before subscribing to the service. The Http request is asynchronous, and until it completes, the records property will be undefined which will result in an error when the grid tries to bind to it. You should either initialize it with a default value or use a BehaviorSubject.

and in the template of the component:

Note: The grid autoGenerate property is best to be avoided when binding to remote data for now. It assumes that the data is available in order to inspect it and generate the appropriate columns. This is usually not the case until the remote service responds, and the grid will throw an error. Making autoGenerate available, when binding to remote service, is on our roadmap for future versions.

Complex Data Binding

The IgxGridComponent supports binding to complex objects (inluding nesting deeper than one level) through a 'path' of properties in the data record.

Take a look at the following data model:

For example, in order to display the weights of a given amino acid in the grid the following snippet will suffice

Refer to the sample below for additional information. This type of binding supports all the default functionality that you would expect from the grid. That is all sorting and filtering operations work out of the box without any additional configuration. Same goes for grouping and editing operations with or without transactions as well as the ability to template the cells of the bound column.

Warning

The grids do not support this kind of binding for primary key, foreign key and child key properties where applicable.

An alternative way to bind complex data, or to visualize composite data (from more than one column) in the IgxGrid is to use a custom body template for the column. Generally, one can:

  • use the value of the cell, that contains the nested data
  • use the cell object in the template, from which to access the rowData, therefore retrieve any value from it, i.e cell.rowData[field]

and interpolate it those in the template.

Below is the data that we are going to use:

The custom template for the column, that will render the nested data:

And the result from this configuration is:

Working with Flat data

The flat data binding approach is similar to the one that we already described above, but instead of cell value we are going to use the rowData property of the IgxRowDirective.

Since the Angular grid is a component for rendering, manipulating and preserving data records, having access to every data record gives you the opportunity to customize the approach of handling it. The rowData property provides you this opportunity.

Below is the data that we are going to use:

The custom template:

Keep in mind that with the above defined template you will not be able to make editing operations, so we need an editor template.

And the result is:

Keyboard Navigation

Grid's keyboard navigation provides a rich variety of keyboard interactions for the user. It enhances accessibility and allows intuitive navigation through any type of elements inside (cell, row, column header, toolbar, footer, etc.). Check out these resources for more information:

  • Blog post - Improving Usability, Accessibility and ARIA Compliance with Grid keyboard navigation
Angular Material Grid

State Persistence

Achieving a state persistence framework is easier than ever by using the new built-in IgxGridState directive.

Sizing

Angular Material Grid List

See the Grid Sizing topic.

Known Limitations

LimitationDescription
Column widths set in percentage and pxCurrently we do not support mixing of column widths with % and px.
When trying to filter a column of type numberIf a value different than number is entered into the filtering input, NaN is returned due to an incorrect cast.
Grid width does not depend on the column widthsThe width of all columns does not determine the spanning of the grid itself. It is determined by the parent container dimensions or the defined grid's width.
Grid nested in parent containerWhen grid's width is not set and it is placed in a parent container with defined dimensions, the grid spans to this container.
Grid OnPush ChangeDetectionStrategyThe grid operates with ChangeDetectionStrategy.OnPush so whenever some customization appears make sure that the grid is notified about the changes that happens.
Columns have a minimum allowed column width. Depending on the displayDensity option, they are as follows:
'compact': 56px
'cosy': 64px
'comfortable ': 80px
If width less than the minimum allowed is set it will not affect the rendered elements. They will render with the minimum allowed width for the corresponding displayDensity. This may lead to an unexpected behavior with horizontal virtualization and is therefore not supported.
Row height is not affected by the height of cells that are not currently rendered in view.Because of virtualization a column with a custom template (that changes the cell height) that is not in the view will not affect the row height. The row height will be affected only while the related column is scrolled in the view.

Angular Material Grid Paging

Note

Angular Material Grid Demo

igxGrid uses igxForOf directive internally hence all igxForOf limitations are valid for igxGrid. For more details see igxForOf Known Issues section.

API References

Angular Material Grid Table

Additional Resources

Angular Material Grid Examples

Our community is active and always welcoming to new ideas.