DataTable DataTable displays data in tabular format.

Import


import {DataTable} from 'primeng/primeng';

Getting Started

DataTable requires a value as an array of objects and a collection of column configurations. Throughout the samples, a car interface having vin, brand, year and color properties are 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[];

    cols: Column[];

    constructor(private carService: CarService) { }

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

        this.cols = [
            {field: 'vin', headerText: 'Vin'},
            {field: 'brand', headerText: 'Brand'},
            {field: 'year', headerText: 'Year'},
            {field: 'color', headerText: 'Color'}
        ];
    }
}

List of cars are bound to the value property and column definitions are configured using columns property.


<p-dataTable [value]="cars" [columns]="cols"></p-dataTable>

Column API

Column interface defines various options to specify corresponding features.


export interface Column {
    field;              //Property of a row data
    header?;            //Header text of a column
    footer?;            //Footer text of a column
    sortable?;          //Defines if a column is sortable
    editable?;          //Defines if a column is editable
    filter?;            //Defines if a column can be filtered
    filterMatchMode?;   //Defines filterMatchMode; "startsWith", "contains" or "endsWidth"
    rowspan?;           //RowSpan to be used for grouping
    colspan?;           //Colspan to be used for grouping
    style?;             //Inline style of the column
    styleClass?;        //Style class of the column
}

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" [columns]="cols">
    <header>List of Cars</header>
    <footer>Choose from the list.</footer>
</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]="sales" [columns]="cols" [headerRows]="headerRows"></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" [columns]="cols" [rows]="10" [paginator]="true"></p-dataTable>

See the live example.

Sorting

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


this.cols = [
    {field: 'vin', headerText: 'Vin', sortable: true},
    {field: 'brand', headerText: 'Brand', sortable: true},
    {field: 'year', headerText: 'Year', sortable: true},
    {field: 'color', headerText: 'Color', sortable: true}
];

See the live example.

Filtering

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


this.cols = [
    {field: 'vin', headerText: 'Vin', filter: true},
    {field: 'brand', headerText: 'Brand', filter: true, filterMatchMode: 'startsWith'},
    {field: 'year', headerText: 'Year', filter: true, filterMatchMode: 'contains'},
    {field: 'color', headerText: 'Color', filter: true, filterMatchMode: 'endsWith'}
];

See the live example.

Selection

DataTable provides single and multiple selection modes on click of a row. Metakey is used to unselect a selected row and also to select multiple rows at the same time in multiple mode. Selected rows are bound to the selection property and onRowSelect-onRowUnselect events are provided as optional callbacks.

In single mode, selection binding is an object reference.


export class DataTableDemo implements OnInit {

    cars: Car[];

    cols: Column[];
    
    selectedCar: Car;

    constructor(private carService: CarService) { }

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

        this.cols = [
            {field: 'vin', headerText: 'Vin'},
            {field: 'brand', headerText: 'Brand'},
            {field: 'year', headerText: 'Year'},
            {field: 'color', headerText: 'Color'}
        ];
    }
}


<p-dataTable [value]="cars" [columns]="cols" selectionMode="single" [(selection)]="selectedCar"></p-dataTable>

In multiple mode, selection binding should be an array.


export class DataTableDemo implements OnInit {

    cars: Car[];

    cols: Column[];
    
    selectedCars: Car[];

    constructor(private carService: CarService) { }

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

        this.cols = [
            {field: 'vin', headerText: 'Vin'},
            {field: 'brand', headerText: 'Brand'},
            {field: 'year', headerText: 'Year'},
            {field: 'color', headerText: 'Color'}
        ];
    }
}


<p-dataTable [value]="cars" [columns]="cols" selectionMode="single" [(selection)]="selectedCars"></p-dataTable>

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.


this.cols = [
    {field: 'vin', headerText: 'Vin', editable: true},
    {field: 'brand', headerText: 'Brand', editable: true},
    {field: 'year', headerText: 'Year', editable: true},
    {field: 'color', headerText: 'Color', editable: true}
];


<p-dataTable [value]="cars" [columns]="cols" [editable]="true"></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" [columns]="cols" [resizableColumns]="true"></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" [columns]="cols" [reorderableColumns]="true"></p-dataTable>

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" [columns]="cols" [scrollable]="true" scrollHeight="200"></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" [columns]="cols" [scrollable]="true" [lazy]="true" (onLazyLoad)="loadData($event)" [totalRecords]="totalRecords"></p-dataTable>


    //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
    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" [columns]="cols" [responsive]="true"></p-dataTable>

See the live example.

Attributes

Name Type Default Description
value array null An array of objects to display.
columns array null An array of column definitions.
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.
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.
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.
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.

Events

Name Parameters Description
onRowSelect event.originalEvent: Browser event
event.data: Selected data
Callback to invoke when a row is selected.
onRowUnselect event.originalEvent: Browser event
event.data: Unselected data
Callback to invoke when a row is unselected with metakey.
onColResize event.element: Resized column header Callback to invoke when a column is resized.
onColReorder event.dragIndex: Index of the dragged column
event.dropIndex: Index of the dropped column
event.dropSide: -1 for left side and +1 for right side of dropped column
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 a column is reordered.

<p-dataTable [value]="cars" [columns]="cols" selectionMode="single" [(selection)]="selectedCar" (onRowSelect)="handleRowSelect($event)"></p-dataTable>


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

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.


<p-dataTable [value]="cars" [columns]="cols"></p-dataTable>


export class DataTableDemo implements OnInit {

    cars: Car[];

    cols: Column[];

    constructor(private carService: CarService) { }

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

        this.cols = [
            {field: 'vin', header: 'Vin'},
            {field: 'brand', header: 'Brand'},
            {field: 'year', header: 'Year'},
            {field: 'color', header: 'Color'}
        ];
    }
}