Web Components Grid Overview and Configuration

    The Web Components Grid is used as a feature-rich control for displaying data in a tabular format quickly and easily. Modern grids are complex and are usually packed with a set of features like data selection, excel style filtering, sorting, paging, templating, column moving, exporting to Excel and CSV, and more.

    Grid

    Web Components Grid Example

    In this grid example, you can see how users can do both basic and excel-style filtering, live-data sorting, as well as the use of grid summaries and cell templating. The demo also includes paging set to display 10 items per page.

    Getting Started with Web Components Grid

    Dependencies

    To get started with the Web Components grid, first you need to install the Ignite UI for Web Components package.

    When installing the Web Components grid package, the core, inputs and layout packages must also be installed.

    npm install --save igniteui-webcomponents-core
    npm install --save igniteui-webcomponents-grids
    npm install --save igniteui-webcomponents-inputs
    npm install --save igniteui-webcomponents-layouts
    

    You also need to include the following import to use the grid:

    import 'igniteui-webcomponents-grids/grids/combined.js';
    

    The corresponding styles should also be referenced. You can choose light or dark option for one of the themes and based on your project configuration to import it:

    import 'igniteui-webcomponents-grids/grids/themes/light/bootstrap.css';
    

    Or to link it:

    <link rel='stylesheet' href='node_modules/igniteui-webcomponents-grids/grids/themes/light/bootstrap.css'>
    

    For more details on how to customize the appearance of the grid, you may have a look at the styling section.

    Usage

    Now that we have the grid packages imported, let’s get started with the basic configuration and bind to local data:

    <igc-grid id="grid1" auto-generate="true"></igc-grid>
    
    constructor() {
        let grid1 = document.getElementById("grid1") as IgcGridComponent;
        grid1.data = data;
    }
    

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

    The autoGenerate property tells the grid to auto generate the grid's IgcColumn components 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.

    Editable Web Components Grid

    Each operation for 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 grid with CRUD operations, the 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 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.

    Grid Column Configuration

    IgcColumn is used to define the grid's columns collection and to enable features per column like sorting and filtering. 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:

    <igc-grid id="grid1" auto-generate="false" allow-filtering="true">
        <igc-column field="Name" sortable="true" header=" "></igc-column>
        <igc-column field="AthleteNumber" sortable="true" header="Athlete number" filterable="false"></igc-column>
        <igc-column id="trackProgress" field="TrackProgress" header="Track progress" filterable="false"></igc-column>
    </igc-grid>
    
    constructor() {
        var grid1 = this.grid1 = document.getElementById('grid1') as IgcGridComponent;
    
        this._bind = () => {
            grid1.data = this.data;
        }
    
        this._bind();
    }
    

    Header Template

    The header template can be set to modify the column headers. The snippets below show you how to format the header text to upper case.

    <igc-column id="name" field="Name"></igc-column>
    
    constructor() {
        var name = this.name = document.getElementById('name') as IgcColumnComponent;
    
        this._bind = () => {
            name.headerTemplate = this.nameHeaderTemplate;
        }
    
        this._bind();
    }
    
    public nameHeaderTemplate = (ctx: IgcColumnTemplateContext) => {
        return html`
            ${this.formatUppercase(ctx.column.field)}
        `;
    }
    
    public formatUppercase(value: string) {
        return value.toUpperCase();
    }
    
    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.

    <igc-column id="productName" field="ProductName" header="Product Name" groupable="true" has-summary="true"></igc-column>
    
    constructor() {
        var productName = this.productName = document.getElementById('productName') as IgcColumnComponent;
    
        this._bind = () => {
            productName.headerTemplate = this.productNameHeaderTemplate;
        }
    
        this._bind();
    }
    
    public productNameHeaderTemplate = (ctx: IgcCellTemplateContext) => {
        return html`
            <div class="text">${ctx.cell.column.field}</div>
            <igc-icon click="${toggleSummary(ctx.cell.column)}" [attr.draggable]="false">functions</igc-icon>
        `;
    }
    
    public toggleSummary(column: IgxColumnComponent) {
    }
    

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

    Cell Template

    When cell template is set it changes all the 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' text could be formatted e.g. as title case.

    <igc-column id="name" field="Name"></igc-column>
    
    constructor() {
        var name = this.name = document.getElementById('name') as IgcColumnComponent;
    
        this._bind = () => {
            name.bodyTemplate = this.nameCellTemplate;
        }
    
        this._bind();
    }
    
    public nameCellTemplate = (ctx: IgcCellTemplateContext) => {
        return html`
            ${this.formatTitleCase(ctx.cell.value)}
        `;
    }
    
    public formatTitleCase(value: string) {
    }
    

    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 GridCell instance itself as shown below:

    <igc-grid id="grid" auto-generate="false">
        <igc-column id="name" field="Name" data-type="string"></igc-column>
        <igc-column id="subscription" field="Subscription" data-type="boolean"></igc-column>
    </igc-grid>
    
    constructor() {
        var grid = this.grid = document.getElementById('grid') as IgcGridComponent;
        var name = this.name = document.getElementById('name') as IgcColumnComponent;
        var subscription = this.subscription = document.getElementById('subscription') as IgcColumnComponent;
    
        this._bind = () => {
            grid.data = this.data;
            name.bodyTemplate = this.nameCellTemplate;
            subscription.bodyTemplate = this.subscriptionCellTemplate;
        }
    
        this._bind();
    }
    
    public nameCellTemplate = (ctx: IgcCellTemplateContext) => {
        return html`
            <span tabindex="0" onkeydown="${this.deleteRow(ctx.cell.id)}">${this.formatTitleCase(ctx.cell.value)}</span>
        `;
    }
    
    public subscriptionCellTemplate = (ctx: IgcCellTemplateContext) => {
        return html`
            <input type="checkbox" value="${ctx.cell.value}" onchange="${this.updateValue(ctx.cell.value)}" />
        `;
    }
    
    public updateValue(value: boolean) {
    }
    
    public deleteRow(rowId: number) {
    }
    
    public formatTitleCase(value: string) {
    }
    
    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.

    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 column to true.

    <igc-column id="price" field="Price" data-type="number" editable="true"></igc-column>
    
    constructor() {
        var price = this.price = document.getElementById('price') as IgcColumnComponent;
    
        this._bind = () => {
            price.inlineEditorTemplate = this.priceCellTemplate;
        }
    
        this._bind();
    }
    
    public priceCellTemplate = (ctx: IgcCellTemplateContext) => {
        return html`
            <label>
                Enter the new price tag
            </label>
            <input name="price" type="number" value="${ctx.cell.value}" onchange="${this.updateValue(ctx.cell.value)}"  />
        `;
    }
    
    public updateValue(value: number) {
    }
    

    Make sure to check the API for the GridCell 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 IgcColumn 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.

    <igc-grid>
        <!-- Column declarations -->
    </igc-grid>
    
    var user = this.user = document.getElementById('user') as IgcColumnComponent;
    // Return the appropriate template based on some condition.
    // For example saved user settings, viewport size, etc.
    user.bodyTemplate = this.smallView;
    
    public normalViewTemplate = (ctx: IgcCellTemplateContext) => {
        return html`
            <div class="user-details">${ ctx.cell.value }</div>
            <user-details-component></user-details-component>
        `;
    }
    
    public smallViewTemplate = (ctx: IgcCellTemplateContext) => {
        return html`
            <div class="user-details-small">${ ctx.cell.value }</div>
        `;
    }
    

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

    public initColumns(column: IgcGridColumn) {
        const column: IgcGridComponent = column;
        if (column.field === 'ProductName') {
            column.sortable = true;
            column.editable = true;
        }
    }
    

    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

    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:

    <igc-column id="orderDate" field="OrderDate" data-type="date"></igc-column>
    
    private _columnPipeArgs: any | null = null;
        public get columnPipeArgs(): any {
            if (this._columnPipeArgs == null)
            {
                var columnPipeArgs: any = {};
                columnPipeArgs.format = "longDate";
                columnPipeArgs.timezone = "UTC";
                columnPipeArgs.digitsInfo = "1.2-2"
                this._columnPipeArgs = columnPipeArgs;
            }
            return this._columnPipeArgs;
        }
    
    constructor() {
        var orderDate = this.orderDate = document.getElementById('orderDate') as IgcColumnComponent;
    
        this._bind = () => {
            orderDate.pipeArgs = this.columnPipeArgs;
        }
    
        this._bind();
    }
    

    The OrderDate column will respect only the format and timezone properties, while the UnitPrice will only respect the digitsInfo.

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

    Grid Data Structure

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

    const OBJECT_ARRAY = [{
            ObjectKey1: value1,
            ObjectKey2: value2,
            .
            .
            .
            ObjectKeyN: valueN
        },
        .
        .
        .
      }];
    
    const POJO = [{
            ObjectKey1: value1,
            ObjectKey2: value2,
            .
            .
            .
            ObjectKeyN: {
              ObjectKeyN1: value1,
              ObjectKeyN2: value2,
              .
              .
              .
              ObjectKeyNM: valueNM,
            }
        },
        .
        .
        .
      }];
    
    Warning

    The key values must not contain arrays.

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

    Grid Data Binding

    Before going any further with the grid we want to change the grid to bind to remote data service, which is the common scenario in large-scale applications.

    You can do this by fetching the data from a given url receiving a JSON response and assigning it to the northwindEmployees property that will be used as the grid's data source:

    public fetchData(url: string): void {
        fetch(url)
          .then(response => response.json())
          .then(data => this.onDataLoaded(data));
    }
    public onDataLoaded(jsonData: any[]) {
        this.northwindEmployees = jsonData;
      }
    
    @property()
    private northwindEmployees?: any[];
    

    And then you can bind the grid to that data:

    <igc-grid id="grid1" .data="${this.northwindEmployees}">
    

    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 IgcGridComponent supports binding to complex objects (including nesting deeper than one level) through a "path" of properties in the data record.

    Take a look at the following data model:

    interface AminoAcid {
        name: string;
        abbreviation: {
            short: string;
            long: string;
        }
        weight: {
            molecular: number;
            residue: number;
        },
        formula: {
            molecular: string;
            residue: string;
        }
    }
    

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

    <igc-column field="weight.molecular"></igc-column>
    <igc-column field="weight.residue"></igc-column>
    

    An alternative way to bind complex data, or to visualize composite data (from more than one column) in the IgcGridComponent 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 row.data, therefore retrieve any value from it, i.e cell.row.data[field] and cell.row.data[field][nestedField] and interpolate those in the template.

    <igc-column id="abbreviationLong" field="abbreviation.long"></igc-column>
    
    constructor() {
        var abbreviationLong = this.abbreviationLong = document.getElementById('abbreviationLong') as IgcColumnComponent;
    
        this._bind = () => {
            abbreviationLong.bodyTemplate = this.abbreviationLongCellTemplate;
        }
    
        this._bind();
    }
    
    public abbreviationLongCellTemplate = (ctx: IgcCellTemplateContext) => {
        return html`
            <div>
                <div>
                    ${ ctx.cell.value }
                    ${ this.getName(ctx.cell.id) }
                    ${ this.getWeight(ctx.cell.id) }
                </div>
            </div>
        `;
    }
    
    public getName(rowId: number){
        //row.data['name']
    }
    public getWeight(rowId: number){
        //row.data['weight']['molecular']
    }
    

    Here is an example on how body template is used to display complex data. Below is the data that we are going to use:

    export const EMPLOYEE_DATA = [
        {
            Age: 55,
            Employees: [
                {
                    Age: 43,
                    HireDate: new Date(2011, 6, 3),
                    ID: 3,
                    Name: "Michael Burke",
                    Title: "Senior Software Developer"
                },
                {
                    Age: 29,
                    HireDate: new Date(2009, 6, 19),
                    ID: 2,
                    Name: "Thomas Anderson",
                    Title: "Senior Software Developer"
                },
                {
                    Age: 31,
                    HireDate: new Date(2014, 8, 18),
                    ID: 11,
                    Name: "Monica Reyes",
                    Title: "Software Development Team Lead"
                },
                {
                    Age: 35,
                    HireDate: new Date(2015, 9, 17),
                    ID: 6,
                    Name: "Roland Mendel",
                    Title: "Senior Software Developer"
                }],
            HireDate: new Date(2008, 3, 20),
            ID: 1,
            Name: "John Winchester",
            Title: "Development Manager"
        }
    ]
    

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

    <igc-column id="employees" field="Employees" header="Employees" width="40%"></igc-column>
    
    constructor() {
        var employees = this.employees = document.getElementById('employees') as IgcColumnComponent;
    
        this._bind = () => {
            employees.bodyTemplate = this.addressCellTemplate;
        }
    
        this._bind();
    }
    
    public addressCellTemplate = (ctx: IgcCellTemplateContext) => {
        return html`
            <div class="employees-container">
                <igc-expansion-panel >
                    <igc-expansion-panel-header iconPosition="right">
                        <igc-expansion-panel-description>
                            ${this.getName(ctx.cell.id.rowIndex)}
                        </igc-expansion-panel-description>
                    </igc-expansion-panel-header>
                    <igc-expansion-panel-body>
                        <div class="description">
                            <igc-input-group keydown="${this.stop()}" display-density="compact">
                                <label for="title">Title</label>
                                <input type="text" name="title" value="${this.getTitle(ctx.cell.id.rowIndex)}" style="text-overflow: ellipsis;" />
                            </igc-input-group>
                            <igc-input-group keydown="${this.stop()}" display-density="compact" style="width: 15%;">
                                <label for="age">Age</label>
                                <input type="number" name="age" value="${this.getAge(ctx.cell.id.rowIndex)}" />
                            </igc-input-group>
                        </div>
                    </igc-expansion-panel-body>
                </igc-expansion-panel>
            </div>
        `;
    }
    
    public stop() {
    }
    
    public getName(rowId: number) {
    }
    
    public getTitle(rowId: number) {
    }
    
    public getAge(rowId: number) {
    }
    

    And the result from this configuration is:

    Working with Flat Data Overview

    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 data property of the IgcGridRow.

    Since the Web Components 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 data property provides you this opportunity.

    Below is the data that we are going to use:

    export const DATA: any[] = [
        {
            Address: "Obere Str. 57",
            City: "Berlin",
            CompanyName: "Alfreds Futterkiste",
            ContactName: "Maria Anders",
            ContactTitle: "Sales Representative",
            Country: "Germany",
            Fax: "030-0076545",
            ID: "ALFKI",
            Phone: "030-0074321",
            PostalCode: "12209",
            Region: null
        }
    ]
    

    The custom template:

    <igc-column id="address" field="Address" header="Address" width="25%" editable="true"></igc-column>
    
    constructor() {
        var address = this.address = document.getElementById('address') as IgcColumnComponent;
    
        this._bind = () => {
            address.bodyTemplate = this.addressCellTemplate;
        }
    
        this._bind();
    }
    
    public addressCellTemplate = (ctx: IgcCellTemplateContext) => {
        return html`
            <div class="address-container">
            <!-- In the Address column combine the Country, City and PostCode values of the corresponding data record -->
                <span><strong>Country:</strong> ${this.getName(ctx.cell.id.rowIndex)}</span>
                <br/>
                <span><strong>City:</strong> ${this.getCity(ctx.cell.id.rowIndex)}</span>
                <br/>
                <span><strong>Postal Code:</strong> ${this.getPostalCode(ctx.cell.id.rowIndex)}</span>
            </div>
        `;
    }
    
    public getCountry(rowId: number) {
    }
    
    public getCity(rowId: number) {
    }
    
    public getPostalCode(rowId: number) {
    }
    

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

    <igc-column id="address" field="Address" data-type="number" width="25%" editable="true"></igc-column>
    
    constructor() {
        var address = this.address = document.getElementById('address') as IgcColumnComponent;
    
        this._bind = () => {
            address.inlineEditorTemplate = this.addressEditCellTemplate;
        }
    
        this._bind();
    }
    
    public addressEditCellTemplate = (ctx: IgcCellTemplateContext) => {
        return html`
            <div class="address-container">
                <span>
                    <strong>Country:</strong> ${this.getName(ctx.cell.id)}
                    <igc-input-group width="100%">
                            <input onchange="${this.updateCountry(ctx.cell.id)}" />
                    </igc-input-group>
                </span>
                <br/>
                <span>
                    <strong>City:</strong> ${this.getCity(ctx.cell.id)}
                    <igc-input-group width="100%">
                            <input onchange="${this.updateCity(ctx.cell.id)}" />
                    </igc-input-group>
                </span>
                <br/>
                <span>
                    <strong>Postal Code:</strong> ${this.getPostalCode(ctx.cell.id)}
                    <igc-input-group width="100%">
                            <input onchange="${this.updatePostalCode(ctx.cell.id)}" />
                    </igc-input-group>
                </span>
                <br/>
            </div>
        `;
    }
    
    public updateCountry(rowId: number) {
    }
    
    public updateCity(rowId: number) {
    }
    
    public updatePostalCode(rowId: number) {
    }
    

    Working with Flat Data Example

    Using code snippets from previous section will result in the following example of IgcGridComponent

    Keyboard Navigation

    Keyboard navigation of the IgcGridComponent 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.).

    Styling Web Components Grid

    Note

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

    In addition to the predefined themes, the grid could be further customized by setting some of the available CSS properties. In case you would like to change the header background and text color, you need to set a class for the grid first:

    <igc-grid class="grid">
    

    Then set the --header-background and --header-text-color CSS properties for that class:

    .grid {
        --header-background: #494949;
        --header-text-color: #FFF;
    }
    

    Known Limitations

    Limitation Description
    Column widths set in percentage and px Currently we do not support mixing of column widths with % and px.
    When trying to filter a column of type number If 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 widths The 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 container When 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 ChangeDetectionStrategy The 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.

    API References

    Additional Resources

    Our community is active and always welcoming to new ideas.