DataTable DataTable displays data in tabular format.

Basic

Dynamic Columns

Import


import {DataTableModule,SharedModule} from 'primeng/primeng';

Getting Started

DataTable requires a value as an array of objects and columns defined with p-column component. Throughout the samples, a car interface having vin, brand, year and color properties is used to define an object to be displayed by the datatable. Cars are loaded by a CarService that connects to a server to fetch the cars with a Promise.


export interface Car {
    vin;
    year;
    brand;
    color;
}


import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Car} from '../domain/car';
    
@Injectable()
export class CarService {
    
    constructor(private http: Http) {}

    getCarsSmall() {
        return this.http.get('/showcase/resources/data/cars-small.json')
                    .toPromise()
                    .then(res => <Car[]> res.json().data)
                    .then(data => { return data; });
    }
}

Following sample datatable has 4 columns and retrieves the data from a service on init.


export class DataTableDemo implements OnInit {

    cars: Car[];

    constructor(private carService: CarService) { }

    ngOnInit() {
        this.carService.getCarsSmall().then(cars => this.cars = cars);
    }
}

List of cars are bound to the value property and columns are defined using p-column component.


<p-dataTable [value]="cars">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>

Column Component

Column component defines various options to specify corresponding features.

Attributes

Name Type Default Description
field string null Property of a row data.
header string null Header text of a column.
footer string null Footer text of a column.
sortable any false Defines if a column is sortable.
sortFunction function null Sort function for custom sorting.
editable boolean false Defines if a column is editable.
filter boolean false Defines if a column can be filtered.
filterMatchMode string null Defines filterMatchMode; "startsWith", "contains" or "endsWidth".
rowspan string null Number of rows to span for grouping.
colspan string null Number of columns to span for grouping.
style string null Inline style of the column.
styleClass string null Style class of the column.
hidden boolean false Controls visiblity of the column.
expander boolean false Displays an icon to toggle row expansion.
selectionMode string null Defines column based selection mode, options are "single" and "checkbox".

<p-column field="vin" header="Vin" [sortable]="true"></p-column>

Dynamic Colums

Columns can be instantiated using an array as well by iterating with ngFor.


export class DataTableDemo implements OnInit {

    cars: Car[];
    
    cols: any[];

    constructor(private carService: CarService) { }

    ngOnInit() {
        this.carService.getCarsSmall().then(cars => this.cars = cars);
        
        this.cols = [
            {field: 'vin', header: 'Vin'},
            {field: 'year', header: 'Year'},
            {field: 'brand', header: 'Brand'},
            {field: 'color', header: 'Color'}
        ];
    }
}


<p-dataTable [value]="cars">
    <p-column *ngFor="let col of cols" [field]="col.field" [header]="col.header"></p-column>
</p-dataTable>

Templates

Field data of a corresponding row is displayed as the cell content by default, this can be customized using templating. The implicit variable is the column definition and data of current row can be accessed using rowData property. In addition index of the current can be access using the optional rowIndex variable.


<p-column field="color" header="Color">
    <template let-col #car="rowData" #ri="rowIndex">
        <span">{{car[col.field]}}</span>
    </template>
</p-column>
<p-column>
    <template let-car="rowData">
        <button type="button" pButton (click)="selectCar(car)" icon="fa-search"></button>
    </template>
</p-column>

See the live example.

Facets

Header and Footer are the two sections aka facets that are capable of displaying custom content.


import {Header} from 'primeng/primeng';
import {Footer} from 'primeng/primeng';


<p-dataTable [value]="cars">
    <header>List of Cars</header>
    <footer>Choose from the list.</footer>
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>

See the live example.

Grouping

Columns can be grouped at header and footer using headerRows and footerRows properties that both define an array of columns each having colspan and rowspan.


<p-dataTable [value]="cars" [headerRows]="headerRows">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>


this.headerRows = [
    {
        columns: [
            {headerText: 'Brand', rowspan: 3},
            {headerText: 'Sale Rate', colspan: 4}
        ]
    },
    {
        columns: [
            {headerText: 'Brand', colspan: 2},
            {headerText: 'Sale Rate', colspan: 2}
        ]
    },
    {
        columns: [
            {headerText: 'Last Year'},
            {headerText: 'This Year'},
            {headerText: 'Last Year'},
            {headerText: 'This Year'}
        ]
    }
];

See the live example.

Paginator

Pagination is enabled by setting paginator property to true, rows attribute defines the number of rows per page and pageLinks specify the the number of page links to display. See paginator component for more information.


<p-dataTable [value]="cars" [rows]="10" [paginator]="true">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>

See the live example.

Sorting

Simply enabling sortable property at column object is enough to make a column sortable.


<p-column field="vin" header="Vin" sortable="true"></p-column>

By default sorting is executed on the clicked column. To do multiple field sorting, set sortMode property to "multiple" and use metakey when clicking on another column.


<p-dataTable [value]="cars" [sortMode]="multiple">

In case you'd like to display the table as sorted by default initially on load, use the sortField-sortOrder properties in single mode.


<p-dataTable [value]="cars" sortField="year" [sortOrder]="1">
    <p-column field="vin" header="Vin" sortable="true"></p-column>
    <p-column field="year" header="Year" sortable="true"></p-column>
    <p-column field="brand" header="Brand" sortable="true"></p-column>
    <p-column field="color" header="Color" sortable="true"></p-column>
</p-dataTable>

In multiple mode, use the multiSortMeta property and bind an array of SortMeta objects.


<p-dataTable [value]="cars" [multiSortMeta]="multiSortMeta">
    <p-column field="vin" header="Vin" sortable="true"></p-column>
    <p-column field="year" header="Year" sortable="true"></p-column>
    <p-column field="brand" header="Brand" sortable="true"></p-column>
    <p-column field="color" header="Color" sortable="true"></p-column>
</p-dataTable>


this.multiSortMeta = [];
this.multiSortMeta.push({field: 'year', order: 1});
this.multiSortMeta.push({field: 'brand', order: -1});

To customize sorting, set sortable option to custom and define a sortFunction that sorts the list.


<p-dataTable [value]="cars" [multiSortMeta]="multiSortMeta">
    <p-column field="vin" header="Vin" sortable="true"></p-column>
    <p-column field="year" header="Year" sortable="custom" (sortFunction)="mysort($event)"></p-column>
    <p-column field="brand" header="Brand" sortable="true"></p-column>
    <p-column field="color" header="Color" sortable="true"></p-column>
</p-dataTable>


mysort(event) {
    //event.field = Field to sort
    //event.order = Sort order
}

See the live example.

Filtering

Filtering is enabled by setting the filter property as true on a column. Default match mode is "startsWith" and this can be configured using filterMatchMode property that also accepts "contains" and "endsWith".


<p-column field="vin" header="Vin (startsWith)" [filter]="true"></p-column>
<p-column field="year" header="Year (contains)" [filter]="true" filterMatchMode="contains"></p-column>
<p-column field="brand" header="Brand (startsWith)" [filter]="true"></p-column>
<p-column field="color" header="Color (endsWith)" [filter]="true" filterMatchMode="endsWith"></p-column>

An optional global filter feature is available to search all fields with the same keyword, to enable this place an input component whose keyup event would be listened for filtering and bind the local template variable name of it to the global filter property.


<input #gb type="text" placeholder="Global search">
<p-dataTable [value]="cars" [rows]="10" [globalFilter]="gb">

See the live example.

Selection

DataTable provides single and multiple selection modes on click of a row. Selected rows are bound to the selection property and onRowSelect-onRowUnselect events are provided as optional callbacks. Alternatively column based selection can be done using radio buttons or checkboxes using selectionMode of a particular column.

In single mode, selection binding is an object reference.


export class DataTableDemo implements OnInit {

    cars: Car[];
    
    selectedCar: Car;

    constructor(private carService: CarService) { }

    ngOnInit() {
        this.carService.getCarsSmall().then(cars => this.cars = cars);
    }
}


<p-dataTable [value]="cars" selectionMode="single" [(selection)]="selectedCar">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>

In multiple mode, selection binding should be an array.


export class DataTableDemo implements OnInit {

    cars: Car[];
    
    selectedCars: Car[];

    constructor(private carService: CarService) { }

    ngOnInit() {
        this.carService.getCarsSmall().then(cars => this.cars = cars);
    }
}


<p-dataTable [value]="cars" selectionMode="single" [(selection)]="selectedCars">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>

If you prefer a radioButton or a checkbox instead of a row click, use the selectionMode of a column instead. Following datatable displays a checkbox at the first column of each row and automatically adds a header checkbox to toggle selection of all rows.


<p-dataTable [value]="cars" [(selection)]="selectedCars">
    <p-column selectionMode="multiple"></p-column>
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>

See the live example.

ContextMenu

DataTable has exclusive integration with contextmenu component. In order to attach a menu to a datatable, define a local template variable for the menu and bind it to the contextMenu property of the datatable. This enables showing the menu whenever a row is right clicked.


<p-dataTable [value]="cars" selectionMode="single" [(selection)]="selectedCar" [contextMenu]="cm">
    <header>Right Click on Rows for ContextMenu</header>
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>

<p-contextMenu #cm [model]="items"></p-contextMenu>

See the live example.

Editing

Incell editing is enabled by setting editable property true both on datatable and columns, when a cell is clicked edit mode is activated, clicking outside of cell or hitting the enter key switches back to view mode after updating the value.


<p-dataTable [value]="cars" [editable]="true">
    <p-column field="vin" header="Vin" [editable]="true"></p-column>
    <p-column field="year" header="Year" [editable]="true"></p-column>
    <p-column field="brand" header="Brand" [editable]="true"></p-column>
    <p-column field="color" header="Color" [editable]="true"></p-column>
</p-dataTable>

See the live example.

Expandable Rows

Row expansion allows displaying detailed content for a particular row. To use this feature, enable expandableRows property, add an expander column and provide a template for the expanded content.


<p-dataTable [value]="cars" expandableRows="true">
    <p-column expander="true" style="width:22px"></p-column>
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
    <template let-car>
        <div class="ui-grid ui-grid-responsive ui-fluid" style="font-size:16px;padding:20px">
            <div class="ui-grid-row">
                <div class="ui-grid-col-3" style="text-align:center">
                    <img src="showcase/resources/demo/images/car/{{car.brand}}-big.gif">
                </div>
                <div class="ui-grid-col-9">
                    <div class="ui-grid ui-grid-responsive ui-grid-pad">
                        <div class="ui-grid-row">
                            <div class="ui-grid-col-2 label">Vin: </div>
                            <div class="ui-grid-col-10">{{car.vin}}</div>
                        </div>
                        <div class="ui-grid-row">
                            <div class="ui-grid-col-2 label">Year: </div>
                            <div class="ui-grid-col-10">{{car.year}}</div>
                        </div>
                        <div class="ui-grid-row">
                            <div class="ui-grid-col-2 label">Brand: </div>
                            <div class="ui-grid-col-10">{{car.brand}}</div>
                        </div>
                        <div class="ui-grid-row">
                            <div class="ui-grid-col-2 label">Color: </div>
                            <div class="ui-grid-col-10">{{car.color}}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>
</p-dataTable>

See the live example.

Column Resize

Columns can be resized using drag drop by setting the resizableColumns to true. There are two resize modes; "fit" and "expand". Fit is the default one and the overall table width does not change when a column is resized. In "expand" mode, table width also changes along with the column width. onColumnResize is a callback that passes the resized column header as a parameter.


<p-dataTable [value]="cars" [resizableColumns]="true">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>

See the live example.

Column Reordering

Columns can be reordered using drag drop by setting the reorderableColumns to true. onColReorder is a callback that is invoked when a column is reordered.


<p-dataTable [value]="cars" [reorderableColumns]="true">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>

See the live example.

Data Export

DataTable can export its data in CSV format using exportCSV() method.


<p-dataTable #dt [value]="cars">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable> 

<button type="button" pButton icon="fa-file-o" iconPos="left" label="CSV" (click)="dt.exportCSV()"></button>

See the live example.

Scrolling

DataTable supports both horizontal and vertical scrolling by defining scrollWidth and scrollHeight options respectively. The properties can take fixed pixels values or percentages to calculate scroll viewport relative to the parent of the datatable. Sample below uses vertical scrolling where headers are fixed and data is scrollable. In horizontal scrolling, it is important to give fixed widths to columns.


<p-dataTable [value]="cars" [scrollable]="true" scrollHeight="200px">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>

See the live example.

Lazy Loading

Lazy mode is handy to deal with large datasets, instead of loading the entire data, small chunks of data is loaded by invoking onLazyLoad callback everytime paging, sorting and filtering happens. To implement lazy loading, enable lazy attribute and provide a method callback using onLazyLoad that actually loads the data from a remote datasource. onLazyLoad gets an event object that contains information about what to load. It is also important to assign the logical number of rows to totalRecords by doing a projection query for paginator configuration so that paginator displays the UI assuming there are actually records of totalRecords size although in reality they aren't as in lazy mode, only the records that are displayed on the current page exist.


<p-dataTable [value]="cars" [scrollable]="true" [lazy]="true" (onLazyLoad)="loadData($event)" [totalRecords]="totalRecords">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>


loadData(event: LazyLoadEvent) {
    //event.first = First row offset
    //event.rows = Number of rows per page
    //event.sortField = Field name to sort in single sort mode
    //event.sortOrder = Sort order as number, 1 for asc and -1 for dec in single sort mode
    //multiSortMeta: An array of SortMeta objects used in multiple columns sorting. Each SortMeta has field and order properties.
    //filters: Filters object having field as key and filter value, filter matchMode as value
    this.cars = //do a request to a remote datasource using a service and return the cars that match the lazy load criteria
}

See the live example.

Responsive

DataTable columns are displayed as stacked in responsive mode if the screen size becomes smaller than a certain breakpoint value. This feature is enabled by setting responsive to true.


<p-dataTable [value]="cars" [responsive]="true">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>

See the live example.

Overlays in Cells

Cells of datatable hides the overflow by default, this prevents overlay of a component like dropdown to be displayed properly. In cases like these, set the style of the column to allow overflow.


<p-column field="color" style="{'overflow':'visible'}">
    <template let-col #car="rowData">
        <p-dropdown></p-dropdown>
    </template>
</p-column>

Attributes

Name Type Default Description
value array null An array of objects to display.
headerRows array null An array of column definitions for column grouping at header.
footerRows array null An array of column definitions for column grouping at footer.
rows number null Number of rows to display per page.
paginator boolean false When specified as true, enables the pagination.
totalRecords number null Number of total records, defaults to length of value when not defined.
pageLinks number null Number of page links to display in paginator.
rowsPerPageOptions array null Array of integer values to display inside rows per page dropdown of paginator
sortMode string single Defines whether sorting works on single column or on multiple columns.
sortField string null Name of the field to sort data by default.
sortOrder number null Order to sort the data by default.
multiSortMeta array null An array of SortMeta objects to sort the data by default in multiple sort mode.
responsive boolean false Defines if the columns should be stacked in smaller screens.
selectionMode string null Specifies the selection mode, valid values are "single" and "multiple".
selection any null Selected row in single mode or an array of values in multiple mode.
editable boolean false Activates incell editing when enabled.
expandableRows boolean false Activates expandable rows feature when true.
expandedRows array null Collection of rows to display as expanded.
globalFilter any null Reference of an input field to use as a global filter.
filterDelay number 300 Delay in milliseconds before filtering the data.
lazy boolean false Defines if data is loaded and interacted with in lazy manner.
resizableColumns boolean false When enabled, columns can be resized using drag and drop.
columnResizeMode boolean false Defines whether the overall table width should change on column resize, valid values are "fit" and "expand".
reorderableColumns boolean false When enabled, columns can be reordered using drag and drop.
scrollable boolean false When specifies, enables horizontal and/or vertical scrolling.
scrollHeight number/string null Height of the scroll viewport, can be pixel as a number or a percentage.
scrollWidth number/string null Width of the scroll viewport, can be pixel as a number or a percentage.
style string null Inline style of the component.
styleClass string null Style class of the component.
contextMenu ContextMenu null Local template varilable of a ContextMenu.
csvSeparator string , Character to use as the csv separator.
emptyMessage string No records found. Text to display when there is no data.
paginatorPosition string bottom Position of the paginator, options are "top","bottom" or "both".

Events

Name Parameters Description
onRowClick event.originalEvent: Browser event
event.data: Selected data
Callback to invoke when a row is clicked.
onRowSelect event.originalEvent: Browser event
event.data: Selected data
event.type: Type of selection, valid values are "row", "radiobutton" and "checkbox"
Callback to invoke when a row is selected.
onRowUnselect event.originalEvent: Browser event
event.data: Unselected data
event.type: Type of unselection, valid values are "row" and "checkbox"
Callback to invoke when a row is unselected with metakey.
onRowDblclick event.originalEvent: Browser event
event.data: Selected data
Callback to invoke when a row is selected with double clicked.
onHeaderCheckboxToggle event.originalEvent: Browser event
event.checked: State of the header checkbox
Callback to invoke when state of header checkbox changes.
onColResize event.element: Resized column header
event.delta: Change of width in number of pixels
Callback to invoke when a column is resized.
onColReorder event.dragIndex: Index of the dragged column
event.dropIndex: Index of the dropped column
event.columns: Columns array after reorder.
Callback to invoke when a column is reordered.
onLazyLoad event.first = First row offset
event.rows = Number of rows per page
event.sortField = Field name to sort with
event.sortOrder = Sort order as number, 1 for asc and -1 for dec
filters: FilterMetadata object having field as key and filter value, filter matchMode as value
Callback to invoke when paging, sorting or filtering happens in lazy mode.
onEditInit event.column: Column object of the cell
event.data: Row data
Callback to invoke when a cell switches to edit mode.
onEdit event.originalEvent: Browser event event.column: Column object of the cell
event.data: Row data
Callback to invoke when cell data is being edited.
onEditComplete event.column: Column object of the cell
event.data: Row data
Callback to invoke when cell edit is completed.
onEditCancel event.column: Column object of the cell
event.data: Row data
Callback to invoke when cell edit is cancelled with escape key.
onPage event.first: Index of first record in page
event.rows: Number of rows on the page
Callback to invoke when pagination occurs.
onSort event.field: Field name of the sorted column
event.order: Sort order as 1 or -1
event.multisortmeta: Sort metadata in multi sort mode. See multiple sorting section for the structure of this object.
Callback to invoke when a column gets sorted.
onFilter event.filters: Filters object having a field as the property key and an object with value, matchMode as the property value.
Callback to invoke when data is filtered.
onRowExpand row: Row data to expand.
Callback to invoke when a row is expanded.
onRowCollapse row: Row data to collapse.
Callback to invoke when a row is collapsed.

<p-dataTable [value]="cars" selectionMode="single" [(selection)]="selectedCar" (onRowSelect)="handleRowSelect($event)">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>


handleRowSelect(event) {
    //event.data = Selected row data
}

Methods

Name Parameters Description
reset - Resets sort, filter and paginator state.
exportCSV - Exports the data in csv format.

<p-dataTable #dt [value]="cars">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>

<button type="button" pButton (click)="update(dt)" label="Reset"></button>


update(dt: DataTable) {
    dt.reset();
}

Styling

Following is the list of structural style classes, for theming classes visit theming page.

Name Element
ui-datatable Container element.
ui-datatable-header Header section.
ui-datatable-footer Footer section.
ui-column-title Title of a column.
ui-sortable-column Sortable column header.
ui-column-filter Filter element in header.
ui-cell-data Data cell in body.
ui-cell-editor Input element for incell editing.
ui-datatable-scrollable-header Container of header in a scrollable table.
ui-datatable-scrollable-header Container of body in a scrollable table.
ui-datatable-scrollable-header Container of footer in a scrollable table.
ui-datatable-responsive Container element of a responsive datatable.

Dependencies

Native component that requires css of PrimeUI DataTable.


<h3 class="first">Basic</h3>
<p-dataTable [value]="cars">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>

<h3>Dynamic Columns</h3>
<p-dataTable [value]="cars">
    <p-column *ngFor="let col of cols" [field]="col.field" [header]="col.header"></p-column>
</p-dataTable>


export class DataTableDemo implements OnInit {

    cars: Car[];
    
    cols: any[];
    
    constructor(private carService: CarService) { }

    ngOnInit() {
        this.carService.getCarsSmall().then(cars => this.cars = cars);
        
        this.cols = [
            {field: 'vin', header: 'Vin'},
            {field: 'year', header: 'Year'},
            {field: 'brand', header: 'Brand'},
            {field: 'color', header: 'Color'}
        ];
    }
}