import DataTable from 'primevue/datatable';
import Column from 'primevue/column';
import ColumnGroup from 'primevue/columngroup'; //optional for column grouping
import Row from 'primevue/row'; //optional for row
<script src="https://unpkg.com/primevue@^3/core/core.min.js"></script>
<script src="https://unpkg.com/primevue@^3/datatable/datatable.min.js"></script>
<script src="https://unpkg.com/primevue@^3/column/column.min.js"></script>
<script src="https://unpkg.com/primevue@^3/columngroup/columngroup.min.js"></script>
<script src="https://unpkg.com/primevue@^3/row/row.min.js"></script>
DataTable requires a value as an array of objects and columns defined with 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 fetch API. Note that this is only for demo purposes, DataTable does not have any restrictions on how the data is provided.
export default class CarService {
getCarsSmall() {
return fetch.get('demo/data/cars-small.json').then(res => res.json()).then(d => d.data);
}
getCarsMedium() {
return fetch.get('demo/data/cars-medium.json').then(res => res.json()).then(d => d.data);
}
getCarsLarge() {
return fetch.get('demo/data/cars-large.json').then(res => res.json()).then(d => d.data);
}
}
Example response;
{
"data": [
{"brand": "Volkswagen", "year": 2012, "color": "Orange", "vin": "dsad231ff"},
{"brand": "Audi", "year": 2011, "color": "Black", "vin": "gwregre345"},
{"brand": "Renault", "year": 2005, "color": "Gray", "vin": "h354htr"},
{"brand": "BMW", "year": 2003, "color": "Blue", "vin": "j6w54qgh"},
{"brand": "Mercedes", "year": 1995, "color": "Orange", "vin": "hrtwy34"},
{"brand": "Volvo", "year": 2005, "color": "Black", "vin": "jejtyj"},
{"brand": "Honda", "year": 2012, "color": "Yellow", "vin": "g43gr"},
{"brand": "Jaguar", "year": 2013, "color": "Orange", "vin": "greg34"},
{"brand": "Ford", "year": 2000, "color": "Black", "vin": "h54hw5"},
{"brand": "Fiat", "year": 2013, "color": "Red", "vin": "245t2s"}
]
}
Following sample datatable has 4 columns and retrieves the data from a service on mount.
<DataTable :value="cars">
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
import CarService from '../../service/CarService';
export default {
data() {
return {
cars: null
}
},
carService: null,
created() {
this.carService = new CarService();
},
mounted() {
this.carService.getCarsSmall().then(data => this.cars = data);
}
}
Column components can be dynamically generated using a v-for as well.
<DataTable :value="cars">
<Column v-for="col of columns" :field="col.field" :header="col.header" :key="col.field"></Column>
</DataTable>
import CarService from '../../service/CarService';
export default {
data() {
return {
columns: null,
cars: null
}
},
carService: null,
created() {
this.carService = new CarService();
this.columns = [
{field: 'vin', header: 'Vin'},
{field: 'year', header: 'Year'},
{field: 'brand', header: 'Brand'},
{field: 'color', header: 'Color'}
];
},
mounted() {
this.carService.getCarsSmall().then(data => this.cars = data);
}
}
Name | Type | Default | Description |
---|---|---|---|
columnKey | any | null | Identifier of a column if field property is not defined. |
field | string | null | Property represented by the column. |
sortField | string | null | Property name to use in sorting, defaults to field. |
filterField | string | null | Property name to use in filtering, defaults to field. |
sortable | any | false | Defines if a column is sortable. |
header | any | null | Header content of the column. |
footer | any | null | Footer content of the column. |
style | object | null | Inline style of header, body and footer cells. |
class | string | null | Style class of header, body and footer cells. |
headerStyle | object | null | Inline style of the column header. |
headerClass | string | null | Style class of the column header. |
bodyStyle | object | null | Inline style of the column body. |
bodyClass | string | null | Style class of the column body. |
footerStyle | object | null | Inline style of the column footer. |
footerClass | string | null | Style class of the column footer. |
showFilterMenu | boolean | true | Whether to display the filter overlay. |
showFilterOperator | boolean | true | When enabled, match all and match any operator selector is displayed. |
showClearButton | boolean | true | Displays a button to clear the column filtering. |
showApplyButton | boolean | true | Displays a button to apply the column filtering. |
showFilterMatchModes | boolean | true | Whether to show the match modes selector. |
showAddButton | boolean | true | When enabled, a button is displayed to add more rules. |
filterMatchModeOptions | array | null | An array of label-value pairs to override the global match mode options. |
maxConstraints | number | 2 | Maximum number of constraints for a column filter. |
excludeGlobalFilter | boolean | false | Whether to exclude from global filtering or not. |
filterHeaderStyle | object | null | Inline style of the column filter header in row filter display. |
filterHeaderClass | string | null | Style class of the column filter header in row filter display. |
filterMenuStyle | object | null | Inline style of the column filter overlay. |
filterMenuClass | string | null | Style class of the column filter overlay. |
selectionMode | string | null | Defines column based selection mode, options are "single" and "multiple". |
expander | boolean | false | Displays an icon to toggle row expansion. |
colspan | number | null | Number of columns to span for grouping. |
rowspan | number | null | Number of rows to span for grouping. |
rowReorder | boolean | false | Whether this column displays an icon to reorder the rows. |
rowReorderIcon | string | pi pi-bars | Icon of the drag handle to reorder rows. |
reorderableColumn | boolean | true | Defines if the column itself can be reordered with dragging. |
rowEditor | boolean | false | When enabled, column displays row editor controls. |
frozen | boolean | false | Whether the column is fixed in horizontal scrolling. |
alignFrozen | string | left | Position of a frozen column, valid values are left and right. |
exportable | boolean | true | Whether the column is included in data export. |
exportHeader | string | null | Custom export header of the column to be exported as CSV. |
exportFooter | string | null | Custom export footer of the column to be exported as CSV. |
filterMatchMode | string | null | Defines the filtering algorithm to use when searching the options. |
hidden | boolean | false | Whether the column is rendered. |
Name | Parameters |
---|---|
header | column: Column node |
body |
data: Row data column: Column node field: Column field index: Row index frozenRow: Is row frozen editorInitCallback: Callback function |
footer | column: Column node |
editor |
data: Row data column: Column node field: Column field index: Row index frozenRow: Is row frozen editorSaveCallback: Callback function editorCancelCallback: Callback function |
filter |
field: Column field filterModel: {value,matchMode} Filter metadata filterCallback: Callback function |
filterheader |
field: Column field filterModel: {value,matchMode} Filter metadata filterCallback: Callback function |
filterfooter |
field: Column field filterModel: {value,matchMode} Filter metadata filterCallback: Callback function |
filterclear |
field: Column field filterModel: {value,matchMode} Filter metadata filterCallback: Callback function |
filterapply |
field: Column field filterModel: {value,matchMode} Filter metadata filterCallback: Callback function |
loading |
data: Row data column: Column node field: Column field index: Row index frozenRow: Is row frozen loadingOptions: Loading options. |
Default table-layout is fixed meaning the cell widths do not depend on their content. If you require cells to scale based on their contents set autoLayout property to true. Note that Scrollable and/or Resizable tables do not support auto layout due to technical limitations.
Field data of a corresponding row is displayed as the cell content by default, this can be customized using a body template where current row data and column properties are passed via the slot props. On the other hand, header and footer sections of a column can either be defined with the properties or the templates. Similarly DataTable itself also provides header and footer properties along with the templates for the main header and footer of the table.
<DataTable :value="cars">
<template #header>
<div>
<Button icon="pi pi-refresh" style="float: left"/>
List of Cars
</div>
</template>
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand">
<template #body="slotProps">
<img :src="'demo/images/car/' + slotProps.data.brand + '.png'" :alt="slotProps.data.brand" width="48px"/>
</template>
</Column>
<Column field="color" header="Color"></Column>
<Column headerStyle="width: 8em" bodyStyle="text-align: center">
<template #header>
<Button type="button" icon="pi pi-cog"></Button>
</template>
<template #body="slotProps">
<Button type="button" icon="pi pi-search" class="p-button-success" style="margin-right: .5em"></Button>
<Button type="button" icon="pi pi-pencil" class="p-button-warning"></Button>
</template>
</Column>
<template #footer>
In total there are {{cars ? cars.length : 0 }} cars.
</template>
</DataTable>
In addition to the regular table, a smal and a large version are available with different paddings. For a table with smaller paddings use p-datatable-sm class and for a larger one use p-datatable-lg.
<DataTable :value="cars" class="p-datatable-sm">
<template #header>
Small Table
</template>
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
<DataTable :value="cars">
<template #header>
Normal Table
</template>
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
<DataTable :value="cars" class="p-datatable-lg">
<template #header>
Large Table
</template>
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
Columns can be grouped at header and footer sections by defining a ColumnGroup with nested rows and columns.
<DataTable :value="sales">
<ColumnGroup type="header">
<Row>
<Column header="Brand" :rowspan="3" />
<Column header="Sale Rate" :colspan="4" />
</Row>
<Row>
<Column header="Sales" :colspan="2" />
<Column header="Profits" :colspan="2" />
</Row>
<Row>
<Column header="Last Year" />
<Column header="This Year" />
<Column header="Last Year" />
<Column header="This Year" />
</Row>
</ColumnGroup>
<Column field="brand" />
<Column field="lastYearSale" />
<Column field="thisYearSale" />
<Column field="lastYearProfit" />
<Column field="thisYearProfit" />
<ColumnGroup type="footer">
<Row>
<Column footer="Totals:" :colspan="3" />
<Column footer="$506,202" />
<Column footer="$531,020" />
</Row>
</ColumnGroup>
</DataTable>
Pagination is enabled by setting paginator property to true and defining the rows property defines the number of rows per page. See the
<DataTable :value="cars" :paginator="true" :rows="10">
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
paginatorstart and paginatorend templates are available to specify custom content at the left and right side.
<DataTable :value="cars" :paginator="true" :rows="10">
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
<template #paginatorstart>
<Button type="button" icon="pi pi-refresh" />
</template>
<template #paginatorend>
<Button type="button" icon="pi pi-cloud" />
</template>
</DataTable>
Paginator can also be programmed programmatically using a binding to the first property that defines the index of the first element to display. For example setting first to zero will reset the paginator to the very first page. This property also supports v-model in case you'd like your binding to be updated whenever the user changes the page.
<DataTable :value="cars" :paginator="true" :rows="10" :first="firstRecordIndex">
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
Enabling sortable property at column component would be enough to make a column sortable. The property to use when sorting is the field by default and can be customized using the sortField.
<DataTable :value="cars">
<Column field="vin" header="Vin" :sortable="true"></Column>
<Column field="year" header="Year" :sortable="true"></Column>
<Column field="brand" header="Brand" :sortable="true"></Column>
<Column field="color" header="Color" :sortable="true"></Column>
</DataTable>
By default sorting is executed on the clicked column only. To enable multiple field sorting, set sortMode property to "multiple" and use metakey when clicking on another column.
<DataTable :value="cars" sortMode="multiple">
<Column field="vin" header="Vin" :sortable="true"></Column>
<Column field="year" header="Year" :sortable="true"></Column>
<Column field="brand" header="Brand" :sortable="true"></Column>
<Column field="color" header="Color" :sortable="true"></Column>
</DataTable>
In case you'd like to display the table as sorted per a single column by default on mount or programmatically apply sort, use sortField and sortOrder properties. These two properties also support the v-model directive to get updated when the user applies sort a column.
<DataTable :value="cars" sortField="year" :sortOrder="1">
<Column field="vin" header="Vin" :sortable="true"></Column>
<Column field="year" header="Year" :sortable="true"></Column>
<Column field="brand" header="Brand" :sortable="true"></Column>
<Column field="color" header="Color" :sortable="true"></Column>
</DataTable>
<DataTable :value="cars" sortField="dynamicSortField" :sortOrder="dynamicSortOrder">
<Column field="vin" header="Vin" :sortable="true"></Column>
<Column field="year" header="Year" :sortable="true"></Column>
<Column field="brand" header="Brand" :sortable="true"></Column>
<Column field="color" header="Color" :sortable="true"></Column>
</DataTable>
In multiple mode, use the multiSortMeta property and bind an array of SortMeta objects instead.
<DataTable :value="cars" sortMode="multiple" :multiSortMeta="multiSortMeta">
<Column field="vin" header="Vin" :sortable="true"></Column>
<Column field="year" header="Year" :sortable="true"></Column>
<Column field="brand" header="Brand" :sortable="true"></Column>
<Column field="color" header="Color" :sortable="true"></Column>
</DataTable>
data() {
return {
multiSortMeta: [
{field: 'year', order: 1},
{field: 'brand', order: -1}
]
}
}
DataTable has advanced filtering capabilities that does the heavy lifting while providing flexible customization. Filtering has two layout alternatives defined with the filterDisplay. In row setting, filter elements are displayed in a separate row at the header section whereas in menu mode filter elements are displayed inside an overlay. Filter metadata is specified using the filters as a v-model and UI elements for the filtering are placed inside the filter template. The template filter gets a filterModel and filterCallback, use filterModel.value to populate the filter with your own form components and call the filterCallback with the event of your choice like @input, @change, @click.
import CustomerService from '../../service/CustomerService';
import {FilterMatchMode} from 'primevue/api';
export default {
data() {
return {
customers: null,
filters: {
'name': {value: null, matchMode: FilterMatchMode.STARTS_WITH}
}
}
},
created() {
this.customerService = new CustomerService();
},
mounted() {
this.customerService.getCustomersLarge().then(data => this.customers = data);
}
}
Input field is displayed in a separate header row.
<DataTable :value="customers1"
dataKey="id" v-model:filters="filters" filterDisplay="row" :loading="loading">
<Column field="name" header="Name">
<template #filter="{filterModel,filterCallback}">
<InputText type="text" v-model="filterModel.value" @keydown.enter="filterCallback()" class="p-column-filter" :placeholder="`Search by name - ${filterModel.matchMode}`"/>
</template>
</Column>
</DataTable>
Input field is displayed in an overlay.
<DataTable :value="customers1"
dataKey="id" v-model:filters="filters" filterDisplay="menu" :loading="loading">
<Column field="name" header="Name">
<template #filter="{filterModel,filterCallback}">
<InputText type="text" v-model="filterModel.value" @keydown.enter="filterCallback()" class="p-column-filter" :placeholder="`Search by name - ${filterModel.matchMode}`"/>
</template>
</Column>
</DataTable>
In "menu" display, it is possible to add more constraints to a same filter. In this case, metadata could be an array of constraints. The operator defines whether all or any of the constraints should match.
data() {
return {
customers: null,
filters: {
'name': {operator: FilterOperator.AND, constraints: [{value: null, matchMode: FilterMatchMode.STARTS_WITH}]},
}
}
}
Providing a filters with predefined values would be enough to display the table as filtered by default. This approach can also be used to clear filters progammatically.
data() {
return {
customers: null,
filters: {
'name': {operator: FilterOperator.AND, constraints: [
{value: 'Prime', matchMode: FilterMatchMode.STARTS_WITH},
{value: 'Vue', matchMode: FilterMatchMode.CONTAINS}
]}
}
}
}
Depending on the dataType of the column, suitable match modes are displayed. Default configuration is available at PrimeVue.filterMatchModeOptions which can be used to customize the modes globally for all tables.
import {createApp} from 'vue';
import PrimeVue from 'primevue/config';
import FilterMatchMode from 'primevue/api',
const app = createApp(App);
app.use(PrimeVue, {
filterMatchModeOptions: {
text: [
FilterMatchMode.STARTS_WITH,
FilterMatchMode.CONTAINS,
FilterMatchMode.NOT_CONTAINS,
FilterMatchMode.ENDS_WITH,
FilterMatchMode.EQUALS,
FilterMatchMode.NOT_EQUALS
],
numeric: [
FilterMatchMode.EQUALS,
FilterMatchMode.NOT_EQUALS,
FilterMatchMode.LESS_THAN,
FilterMatchMode.LESS_THAN_OR_EQUAL_TO,
FilterMatchMode.GREATER_THAN,
FilterMatchMode.GREATER_THAN_OR_EQUAL_TO
],
date: [
FilterMatchMode.DATE_IS,
FilterMatchMode.DATE_IS_NOT,
FilterMatchMode.DATE_BEFORE,
FilterMatchMode.DATE_AFTER
]
}
});
If you need to override the match modes for a particular column use the filterMatchModeOptions property and provide an array with label-value pairs.
<Column field="name" header="Name" :filterMatchModeOptions="matchModes">
<template #filter="{filterModel,filterCallback}">
<InputText type="text" v-model="filterModel.value" @keydown.enter="filterCallback()" class="p-column-filter" :placeholder="`Search by name - ${filterModel.matchMode}`"/>
</template>
</Column>
matchModes: [
{label: 'Starts With', value: FilterMatchMode.STARTS_WITH},
{label: 'Contains', value: FilterMatchMode.CONTAINS},
]
Custom filtering is implemented using the FilterService, first register your filter and add it to your filterMatchModeOptions.
import {FilterService} from 'primevue/api';
FilterService.register('myfilter', (a,b) => a === b);
matchModes: [
{label: 'My Filter', "myfilter"},
{label: 'Starts With', value: FilterMatchMode.STARTS_WITH},
{label: 'Contains', value: FilterMatchMode.CONTAINS},
]
Filter menu overlay can be customized even further with various templates including filterheader, filterfooter, filterclear, filterapply. Example here changes the buttons and adds a footer.
<Column header="Country" filterField="country.name">
<template #filter="{filterModel}">
<InputText type="text" v-model="filterModel.value" class="p-column-filter" placeholder="Search by country"/>
</template>
<template #filterclear="{filterCallback}">
<Button type="button" icon="pi pi-times" @click="filterCallback()" class="p-button-secondary"></Button>
</template>
<template #filterapply="{filterCallback}">
<Button type="button" icon="pi pi-check" @click="filterCallback()" class="p-button-success"></Button>
</template>
<template #filterfooter>
<div class="px-3 pt-0 pb-3 text-center font-bold">Customized Buttons</div>
</template>
</Column>
DataTable provides single and multiple selection modes on click of a row. Selected rows are bound to the selection property and updated using the v-model directive. Alternatively column based selection can be done using radio buttons or checkboxes using selectionMode of a particular column. In addition row-select and row-unselect events are provided as optional callbacks.
The dataKey property identifies a unique value of a row in the dataset, it is not mandatory however being able to define it increases the performance of the table signifantly.
In single mode, selection binding is an object reference.
<DataTable :value="cars" v-model:selection="selectedCar" selectionMode="single" dataKey="vin">
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
In multiple mode, selection binding should be an array and multiple items can either be selected using metaKey or toggled individually depending on the value of metaKeySelection property value which is true by default. On touch enabled devices metaKeySelection is turned off automatically. Additionally ShiftKey is supported for range selection.
<DataTable :value="cars" v-model:selection="selectedCars" selectionMode="multiple" dataKey="vin">
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</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.
<DataTable :value="cars" v-model:selection="selectedCars" dataKey="vin">
<Column selectionMode="multiple"></Column>
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
DataTable supports both horizontal and vertical scrolling as well as frozen columns and rows. Scrollable DataTable is enabled using scrollable property and scrollHeight to define the viewport height.
<DataTable :value="cars" :scrollable="true" scrollHeight="400px">
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
Scrollable table uses flex layout so there are a couple of rules to consider when adjusting the widths of columns.
<Column field="vin" header="Vin" style="flex: 0 0 4rem"></Column>
In cases where viewport should adjust itself according to the table parent's height instead of a fixed viewport height, set scrollHeight option as flex. In example below, table is inside a Dialog where viewport size dynamically responds to the dialog size changes such as maximizing.
<Button label="Show" icon="pi pi-external-link" @click="openDialog" />
<Dialog header="Flex Scroll" v-model:visible="dialogVisible" :style="{width: '50vw'}" :maximizable="true" :modal="true" :contentStyle="{height: '300px'}">
<DataTable :value="cars" :scrollable="true" scrollHeight="flex">
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
<template #footer>
<Button label="Yes" icon="pi pi-check" @click="closeDialog" />
<Button label="No" icon="pi pi-times" @click="closeDialog" class="p-button-secondary"/>
</template>
</Dialog>
FlexScroll can also be used for cases where scrollable viewport should be responsive with respect to the window size. See the
<div style="height: calc(100vh - 143px)">
<DataTable :value="cars" :scrollable="true" scrollHeight="flex">
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
</div>
For horizontal scrolling, it is required to set scrollDirection to "horizontal" and give fixed widths to columns.
<DataTable :value="customers" :scrollable="true" scrollDirection="horizontal">
<Column field="id" header="Id" footer="Id" :style="{width:'200px'}"></Column>
<Column field="name" header="Name" footer="Name" :style="{width:'200px'}"></Column>
<Column field="country.name" header="Country" footer="Country" :style="{width:'200px'}"></Column>
<Column field="date" header="Date" footer="Date" :style="{width:'200px'}"></Column>
<Column field="balance" header="Balance" footer="Balance" :style="{width:'200px'}"></Column>
<Column field="company" header="Company" footer="Company" :style="{width:'200px'}"></Column>
<Column field="status" header="Status" footer="Status" :style="{width:'200px'}"></Column>
<Column field="activity" header="Activity" footer="Activity" :style="{width:'200px'}"></Column>
<Column field="representative.name" header="Representative" footer="Representative" :style="{width:'200px'}"></Column>
</DataTable>
Set scrollDirection to "both" and give fixed widths to columns to scroll both ways.
<DataTable :value="customers" :scrollable="true" scrollHeight="400px" scrollDirection="both">
<Column field="id" header="Id" footer="Id" :style="{width:'200px'}"></Column>
<Column field="name" header="Name" footer="Name" :style="{width:'200px'}"></Column>
<Column field="country.name" header="Country" footer="Country" :style="{width:'200px'}"></Column>
<Column field="date" header="Date" footer="Date" :style="{width:'200px'}"></Column>
<Column field="balance" header="Balance" footer="Balance" :style="{width:'200px'}"></Column>
<Column field="company" header="Company" footer="Company" :style="{width:'200px'}"></Column>
<Column field="status" header="Status" footer="Status" :style="{width:'200px'}"></Column>
<Column field="activity" header="Activity" footer="Activity" :style="{width:'200px'}"></Column>
<Column field="representative.name" header="Representative" footer="Representative" :style="{width:'200px'}"></Column>
</DataTable>
Frozen rows are used to fix certain rows while scrolling, this data is defined with the frozenValue property.
<DataTable :value="customers" :frozenValue="lockedCustomers" :scrollable="true" scrollHeight="400px">
<Column field="name" header="Name"></Column>
<Column field="country.name" header="Country"></Column>
<Column field="representative.name" header="Representative"></Column>
<Column field="status" header="Status"></Column>
</DataTable>
Certain columns can be frozen by using the frozen property of the column component. In addition alignFrozen is available to define whether the column should be fixed on the left or right.
<DataTable :value="customers" :scrollable="true" scrollHeight="400px" scrollDirection="both">
<Column field="name" header="Name" :style="{width:'200px'}" frozen></Column>
<Column field="id" header="Id" :style="{width:'100px'}" :frozen="idFrozen"></Column>
<Column field="name" header="Name" :style="{width:'200px'}"></Column>
<Column field="country.name" header="Country" :style="{width:'200px'}"></Column>
<Column field="date" header="Date" :style="{width:'200px'}"></Column>
<Column field="company" header="Company" :style="{width:'200px'}"></Column>
<Column field="status" header="Status" :style="{width:'200px'}"></Column>
<Column field="activity" header="Activity" :style="{width:'200px'}"></Column>
<Column field="representative.name" header="Representative" :style="{width:'200px'}"></Column>
<Column field="balance" header="Balance" :style="{width:'200px'}" frozen alignFrozen="right"></Column>
</DataTable>
Row groups with subheaders have exclusive support for filtering, when the table scrolls the subheaders stay fixed as long as their data are still displayed. No additional configuration is required to enable this feature. View the
Lazy mode is handy to deal with large datasets, instead of loading the entire data, small chunks of data is loaded by invoking corresponding callbacks such as paging and sorting. 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 accordingly.
Lazy loading is implemented by handling page, sort, filter events by making a remote query using the information passed to these events such as first offset, number of rows, sort field for ordering and filters. Note that, in lazy filtering totalRecords should also be updated to align the data with the paginator.
Visit the
Rows can be expanded to display additional content using the expandedRows property with the v-model directive accompanied by a template named "expansion". row-expand and row-collapse are optional callbacks that are invoked when a row is expanded or toggled.
The dataKey property identifies a unique value of a row in the dataset, it is not mandatory in row expansion functionality however being able to define it increases the performance of the table significantly.
<DataTable :value="cars" v-model:expandedRows="expandedRows" dataKey="vin"
@row-expand="onRowExpand" @row-collapse="onRowCollapse">
<template #header>
<div class="table-header-container">
<Button icon="pi pi-plus" label="Expand All" @click="expandAll" />
<Button icon="pi pi-minus" label="Collapse All" @click="collapseAll" />
</div>
</template>
<Column :expander="true" headerStyle="width: 3em" />
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
<template #expansion="slotProps">
<div class="car-details">
<div>
<img :src="'demo/images/car/' + slotProps.data.brand + '.png'" :alt="slotProps.data.brand"/>
<div class="grid">
<div class="col-12">Vin: <b>{{slotProps.data.vin}}</b></div>
<div class="col-12">Year: <b>{{slotProps.data.year}}</b></div>
<div class="col-12">Brand: <b>{{slotProps.data.brand}}</b></div>
<div class="col-12">Color: <b>{{slotProps.data.color}}</b></div>
</div>
</div>
<Button icon="pi pi-search"></Button>
</div>
</template>
</DataTable>
import CarService from '../../service/CarService';
export default {
data() {
return {
cars: null,
expandedRows: []
}
},
carService: null,
created() {
this.carService = new CarService();
},
mounted() {
this.carService.getCarsSmall().then(data => this.cars = data);
},
methods: {
onRowExpand(event) {
this.$toast.add({severity: 'info', summary: 'Row Expanded', detail: 'Vin: ' + event.data.vin, life: 3000});
},
onRowCollapse(event) {
this.$toast.add({severity: 'success', summary: 'Row Collapsed', detail: 'Vin: ' + event.data.vin, life: 3000});
},
expandAll() {
this.expandedRows = this.cars.filter(car => car.vin);
this.$toast.add({severity: 'success', summary: 'All Rows Expanded', life: 3000});
},
collapseAll() {
this.expandedRows = null;
this.$toast.add({severity: 'success', summary: 'All Rows Collapsed', life: 3000});
}
}
}
In cell editing provides a rapid and user friendly way to manipulate the data. The datatable provides a flexible API so that the editing behavior is implemented by the page author whether it utilizes v-model or vuex.
Individual cell editing is configured by setting the editMode to cell, defining editors with the editor template along with the @cell-edit-complete event. The content of the editor defines how the editing is implemented. The editor template receives a clone of the row data and using @cell-edit-complete event the new value can be updated to the model or cancelled. This also provides flexibility to apply conditional logic such as implementing validations.
<h5>Cell Editing</h5>
<DataTable :value="cars" editMode="cell" @cell-edit-complete="onCellEditComplete">
<Column field="vin" header="Vin">
<template #editor="slotProps">
<InputText v-model="slotProps.data[slotProps.field]" />
</template>
</Column>
<Column field="year" header="Year">
<template #editor="slotProps">
<InputText v-model="slotProps.data[slotProps.field]" />
</template>
</Column>
<Column field="brand" header="Brand">
<template #editor="slotProps">
<Dropdown v-model="slotProps.data['brand']" :options="brands" optionLabel="brand" optionValue="value" placeholder="Select a Brand">
<template #option="optionProps">
<div class="p-dropdown-car-option">
<img :alt="optionProps.option.brand" :src="'demo/images/car/' + optionProps.option.brand + '.png'" />
<span>{{optionProps.option.brand}}</span>
</div>
</template>
</Dropdown>
</template>
</Column>
<Column field="color" header="Color">
<template #editor="slotProps">
<InputText v-model="slotProps.data[slotProps.field]" />
</template>
</Column>
</DataTable>
import CarService from '../../service/CarService';
import Vue from 'vue';
export default {
data() {
return {
cars: null,
brands: [
{brand: 'Audi', value: 'Audi'},
{brand: 'BMW', value: 'BMW'},
{brand: 'Fiat', value: 'Fiat'},
{brand: 'Honda', value: 'Honda'},
{brand: 'Jaguar', value: 'Jaguar'},
{brand: 'Mercedes', value: 'Mercedes'},
{brand: 'Renault', value: 'Renault'},
{brand: 'Volkswagen', value: 'Volkswagen'},
{brand: 'Volvo', value: 'Volvo'}
]
}
},
carService: null,
created() {
this.carService = new CarService();
},
methods: {
onCellEditComplete(event) {
let { data, newValue, field } = event;
switch (event.field) {
case 'year':
if (this.isPositiveInteger(newValue))
data[field] = newValue;
else
event.preventDefault();
break;
default:
if (newValue.trim().length > 0)
data[field] = newValue;
else
event.preventDefault();
break;
}
},
isPositiveInteger(val) {
let str = String(val);
str = str.trim();
if (!str) {
return false;
}
str = str.replace(/^0+/, "") || "0";
var n = Math.floor(Number(str));
return n !== Infinity && String(n) === str && n >= 0;
}
},
mounted() {
this.carService.getCarsSmall().then(data => this.cars = data);
}
}
Row Editing is specified by setting editMode as row, defining editingRows with the v-model directive to hold the reference of the editing rows, adding a row editor column to provide the editing controls and implementing @row-edit-save to update the original row data. Note that since editingRows is two-way binding enabled, you may use it to initially display one or more rows in editing more or programmatically toggle row editing.
<h3>Row Editing</h3>
<DataTable :value="cars" editMode="row" dataKey="vin" v-model:editingRows="editingRows" @row-edit-save="onRowEditSave">
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year">
<template #editor="slotProps">
<InputText v-model="slotProps.data[slotProps.field]" autofocus/>
</template>
</Column>
<Column field="brand" header="Brand">
<template #editor="slotProps">
<InputText v-model="slotProps.data[slotProps.field]" />
</template>
</Column>
<Column field="color" header="Color">
<template #editor="slotProps">
<InputText v-model="slotProps.data[slotProps.field]" />
</template>
</Column>
<Column :rowEditor="true" headerStyle="width:7rem" bodyStyle="text-align:center"></Column>
</DataTable>
import CarService from '../../service/CarService';
import Vue from 'vue';
export default {
data() {
return {
cars: null,
editingRows: []
}
},
carService: null,
created() {
this.carService = new CarService();
},
methods: {
onRowEditSave(event) {
let { newData, index } = event;
this.cars[index] = newData;
},
},
mounted() {
this.carService.getCarsSmall().then(data => this.cars = data);
}
}
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. column-resize-end is a callback that passes the resized column header and delta change as a parameter.
<DataTable :value="cars" :resizableColumns="true" columnResizeMode="fit | expand">
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
It is important to note that when you need to change column widths, since table width is 100%, giving fixed pixel widths does not work well as browsers scale them, instead give percentage widths.
<DataTable :value="cars" :resizableColumns="true" columnResizeMode="fit | expand">
<Column field="vin" header="Vin" headerStyle="width: 20%"></Column>
<Column field="year" header="Year" headerStyle="width: 40%"></Column>
<Column field="brand" header="Brand" headerStyle="width: 20%"></Column>
<Column field="color" header="Color" headerStyle="width: 20%"></Column>
</DataTable>
Columns can be reordered using drag drop by setting the reorderableColumns to true. column-reorder is a callback that is invoked when a column is reordered. DataTable keeps the column order state internally using keys that identifies a column using the field property. If the column has no field, use columnKey instead as it is mandatory for columns to have unique keys when reordering is enabled.
<DataTable :value="cars" :reorderableColumns="true">
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
Data can be reordered using drag drop by adding a reorder column that will display an icon as a drag handle along with the row-reorder event which is mandatory to update the new order. Note that the reorder icon can be customized using rowReorderIcon of the column component.
<DataTable :value="cars" @row-reorder="onRowReorder">
<Column :rowReorder="true" headerStyle="width: 3em" />
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
import CarService from '../../service/CarService';
export default {
data() {
return {
cars: null
}
},
carService: null,
created() {
this.carService = new CarService();
},
mounted() {
this.carService.getCarsSmall().then(data => this.cars = data);
},
methods: {
onRowReorder(event) {
//update new order
this.cars = event.value;
}
}
}
Row Grouping comes in two modes, in "subheader" mode rows are grouped by a header row along with an optional group footer. In addition, the groups can be made toggleable by enabling expandableRowGroups as true. On the other hand, the "rowspan" mode uses rowspans instead of a header to group rows. groupRowsBy property defines the field to use in row grouping. Multiple row grouping is available in "rowspan" mode by specifying the groupRowsBy as an array of fields.
Example below demonstrates the all grouping alternatives. Note that data needs to be sorted for grouping which can also be done by the table itself by speficying the sort properties.
<h3>Subheader Grouping</h3>
<DataTable :value="cars" rowGroupMode="subheader" groupRowsBy="brand"
sortMode="single" sortField="brand" :sortOrder="1">
<Column field="brand" header="Brand"></Column>
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="color" header="Color"></Column>
<Column field="price" header="Price"></Column>
<template #groupheader="slotProps">
<span>{{slotProps.data.brand}}</span>
</template>
<template #groupfooter="slotProps">
<td colspan="3" style="text-align: right">Total Price</td>
<td>{{calculateGroupTotal(slotProps.data.brand)}}</td>
</template>
</DataTable>
<h3>Expandable Row Groups</h3>
<DataTable :value="cars" rowGroupMode="subheader" groupRowsBy="brand"
sortMode="single" sortField="brand" :sortOrder="1"
:expandableRowGroups="true" v-model:expandedRowGroups="expandedRowGroups"
@rowgroup-expand="onRowExpand" @rowgroup-collapse="onRowCollapse">
<Column field="brand" header="Brand"></Column>
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="color" header="Color"></Column>
<Column field="price" header="Price"></Column>
<template #groupheader="slotProps">
<span>{{slotProps.data.brand}}</span>
</template>
<template #groupfooter="slotProps">
<td colspan="3" style="text-align: right">Total Price</td>
<td>{{calculateGroupTotal(slotProps.data.brand)}}</td>
</template>
</DataTable>
<h3>RowSpan Grouping</h3>
<DataTable :value="cars" rowGroupMode="rowspan" groupRowsBy="brand"
sortMode="single" sortField="brand" :sortOrder="1">
<Column header="#" headerStyle="width:3em">
<template #body="slotProps">
{{slotProps.index}}
</template>
</Column>
<Column field="brand" header="Brand"></Column>
<Column field="year" header="Year"></Column>
<Column field="vin" header="Vin"></Column>
<Column field="color" header="Color"></Column>
<Column field="price" header="Price"></Column>
</DataTable>
import CarService from '../../service/CarService';
export default {
data() {
return {
cars: null,
expandedRowGroups: null
}
},
carService: null,
created() {
this.carService = new CarService();
},
mounted() {
this.carService.getCarsMedium().then(data => this.cars = data);
},
methods: {
onRowGroupExpand(event) {
this.$toast.add({severity: 'info', summary: 'Row Group Expanded', detail: 'Value: ' + event.data, life: 3000});
},
onRowGroupCollapse(event) {
this.$toast.add({severity: 'success', summary: 'Row Group Collapsed', detail: 'Value: ' + event.data, life: 3000});
},
calculateGroupTotal(brand) {
let total = 0;
if (this.cars) {
for (let car of this.cars) {
if (car.brand === brand) {
total += car.price;
}
}
}
return total;
}
}
}
DataTable can export its data in CSV format using exportCSV() method.
>
<DataTable :value="cars" ref="dt">
<template #header>
<div style="text-align: left">
<Button icon="pi pi-external-link" label="Export" @click="exportCSV($event)" />
</div>
</template>
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
import CarService from '../../service/CarService';
export default {
data() {
return {
cars: null
}
},
carService: null,
created() {
this.carService = new CarService();
},
mounted() {
this.carService.getCarsSmall().then(data => this.cars = data);
},
methods: {
exportCSV() {
this.$refs.dt.exportCSV();
}
}
}
Stateful table allows keeping the state such as page, sort and filtering either at local storage or session storage so that when the page is visited again, table would render the data using its last settings. Enabling state is easy as defining a unique stateKey, the storage to keep the state is defined with the stateStorage property that accepts session for sessionStorage and local for localStorage. Currently following features are supported by TableState; paging, sorting, filtering, column resizing, column reordering, row expansion, row group expansion and row selection.
<DataTable :value="cars" :paginator="true" :rows="10" v-model:filters="filters"
stateStorage="session" stateKey="dt-state-demo-session"
v-model:selection="selectedCar" selectionMode="single" dataKey="vin">
<template #header>
<div style="text-align: right">
<i class="pi pi-search" style="margin: 4px 4px 0px 0px;"></i>
<InputText v-model="filters['global']" placeholder="Global Search" size="50" />
</div>
</template>
<Column field="vin" header="Vin" filterMatchMode="startsWith" :sortable="true">
<template #filter>
<InputText type="text" v-model="filters['vin']" class="p-column-filter" placeholder="Starts with" />
</template>
</Column>
<Column field="year" header="Year" filterMatchMode="contains" :sortable="true">
<template #filter>
<InputText type="text" v-model="filters['year']" class="p-column-filter" placeholder="Contains" />
</template>
</Column>
<Column field="brand" header="Brand" filterMatchMode="equals" :sortable="true">
<template #filter>
<Dropdown v-model="filters['brand']" :options="brands" optionLabel="brand" optionValue="value" placeholder="Select a Brand" class="p-column-filter" :showClear="true">
<template #option="slotProps">
<div class="p-dropdown-car-option">
<img :alt="slotProps.option.brand" :src="'demo/images/car/' + slotProps.option.brand + '.png'" />
<span>{{slotProps.option.brand}}</span>
</div>
</template>
</Dropdown>
</template>
</Column>
<Column field="color" header="Color" filterMatchMode="in" :sortable="true">
<template #filter>
<MultiSelect v-model="filters['color']" :options="colors" optionLabel="name" optionValue="value" placeholder="Select a Color" />
</template>
</Column>
<template #empty>
No records found.
</template>
</DataTable>
import CarService from '../../service/CarService';
export default {
data() {
return {
filters: {},
brands: [
{brand: 'Audi', value: 'Audi'},
{brand: 'BMW', value: 'BMW'},
{brand: 'Fiat', value: 'Fiat'},
{brand: 'Honda', value: 'Honda'},
{brand: 'Jaguar', value: 'Jaguar'},
{brand: 'Mercedes', value: 'Mercedes'},
{brand: 'Renault', value: 'Renault'},
{brand: 'Volkswagen', value: 'Volkswagen'},
{brand: 'Volvo', value: 'Volvo'}
],
colors: [
{name: 'White', value: 'White'},
{name: 'Green', value: 'Green'},
{name: 'Silver', value: 'Silver'},
{name: 'Black', value: 'Black'},
{name: 'Red', value: 'Red'},
{name: 'Maroon', value: 'Maroon'},
{name: 'Brown', value: 'Brown'},
{name: 'Orange', value: 'Orange'},
{name: 'Blue', value: 'Blue'}
],
selectedCar: null,
cars: null
}
},
carService: null,
created() {
this.carService = new CarService();
},
mounted() {
this.carService.getCarsMedium().then(data => this.cars = data);
}
}
DataTable provides exclusive integration with the ContextMenu component using, contextMenu, contextMenuSelection property along with the row-contextmenu event.
<DataTable :value="cars" contextMenu v-model:contextMenuSelection="selectedCar" @row-contextmenu="onRowContextMenu">
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
<ContextMenu :model="menuModel" ref="cm" />
import CarService from '../../service/CarService';
export default {
data() {
return {
cars: null,
selectedCar: null,
menuModel: [
{label: 'View', icon: 'pi pi-fw pi-search', command: () => this.viewCar(this.selectedCar)},
{label: 'Delete', icon: 'pi pi-fw pi-times', command: () => this.deleteCar(this.selectedCar)}
]
}
},
carService: null,
created() {
this.carService = new CarService();
},
mounted() {
this.carService.getCarsSmall().then(data => this.cars = data);
},
methods: {
onRowContextMenu(event) {
this.$refs.cm.show(event.originalEvent);
},
viewCar(car) {
this.$toast.add({severity: 'info', summary: 'Car Selected', detail: car.vin + ' - ' + car.brand});
},
deleteCar(car) {
this.cars = this.cars.filter((c) => c.vin !== car.vin);
this.$toast.add({severity: 'info', summary: 'Car Deleted', detail: car.vin + ' - ' + car.brand});
this.selectedCar = null;
}
}
}
When there is no data, you may use the empty template to display a message.
<DataTable :value="cars">
<template #empty>
No records found
</template>
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
A loading status indicator can be displayed when the loading property is enabled. The icon is customized through loadingIcon property. Additionally an option loading template is available to render as the body until the data is loaded.
<DataTable :value="cars" :loading="loading">
<template #loading>
Loading records, please wait...
</template>
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
import CarService from '../../service/CarService';
export default {
data() {
return {
loading: false,
cars: null
}
},
datasource: null,
carService: null,
created() {
this.carService = new CarService();
},
mounted() {
this.loading = true;
this.carService.getCarsLarge().then(data => {
this.cars = data
this.loading = false;
});
}
}
DataTable responsive layout can be achieved in two ways; first approach is displaying a horizontal scrollbar for smaller screens and second one is defining a breakpoint to display the cells of a row as stacked. Scrollable tables use the scroll layout approach internally and do not require additional configuration.
Set responsiveLayout to scroll to enabled this layout. Note that, when scroll mode is enabled table-layout automatically switches to auto from fixed as a result table widths are likely to differ and resizable columns are not supported. Read more about table-layout for more details.
<DataTable :value="products" responsiveLayout="scroll">
</DataTable>
In stack layout, columns are displayed as stacked after a certain breakpoint. Default is '960px'.
<DataTable :value="products" responsiveLayout="stack" breakpoint="640px">
</DataTable>
Certain rows or cells can easily be styled based on conditions. Cell styling is implemented with templating whereas row styling utilizes the rowClass property which takes the row data as a parameter and returns the style class as a string.
<DataTable :value="cars" :rowClass="rowClass">
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year" bodyStyle="padding: 0">
<template #body="slotProps">
<div :class="['year-cell', {'old-car': slotProps.data.year < 2010}]">
{{slotProps.data.year}}
</div>
</template>
</Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
import CarService from '../../service/CarService';
export default {
data() {
return {
columns: null,
cars: null
}
},
carService: null,
created() {
this.carService = new CarService();
},
mounted() {
this.carService.getCarsSmall().then(data => this.cars = data);
},
methods: {
rowClass(data) {
return data.color === 'Orange' ? 'orange-car': null;
}
}
}
.year-cell {
padding: 0.429em 0.857rem;
&.old-car {
background-color: #41b783;
font-weight: 700;
color: #ffffff;
}
}
.orange-car {
background-color: #344b5f !important;
color: #ffffff !important;
}
Any valid attribute is passed to the root element implicitly, extended properties are as follows;
Name | Type | Default | Description |
---|---|---|---|
value | array | null | An array of objects to display. |
dataKey | string | null | Name of the field that uniquely identifies the a record in the data. |
rows | number | null | Number of rows to display per page. |
first | number | 0 | Index of the first row to be displayed. |
totalRecords | number | null | Number of total records, defaults to length of value when not defined. |
paginator | boolean | false | When specified as true, enables the pagination. |
paginatorPosition | string | bottom | Position of the paginator, options are "top","bottom" or "both". |
alwaysShowPaginator | boolean | true | Whether to show it even there is only one page. |
paginatorTemplate | string |
FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown |
Template of the paginator. See the |
pageLinkSize | number | 5 | Number of page links to display. |
rowsPerPageOptions | array | null | Array of integer values to display inside rows per page dropdown. |
currentPageReportTemplate | string | ({currentPage} of {totalPages}) | Template of the current page report element. |
lazy | boolean | false | Defines if data is loaded and interacted with in lazy manner. |
loading | boolean | false | Displays a loader to indicate data load is in progress. |
loadingIcon | string | pi pi-spinner | The icon to show while indicating data load is in progress. |
sortField | string | null | Property name or a getter function of a row data used for sorting by default |
sortOrder | number | null | Order to sort the data by default. |
defaultSortOrder | number | 1 | Default sort order of an unsorted column. |
multiSortMeta | array | null | An array of SortMeta objects to sort the data by default in multiple sort mode. |
sortMode | string | single | Defines whether sorting works on single column or on multiple columns. |
removableSort | boolean | false | When enabled, columns can have an un-sorted state. |
filters | object | null | Filters object with key-value pairs to define the filters. |
filterDisplay | string | null | Layout of the filter elements, valid values are "row" and "menu". |
filterLocale | string | undefined | Locale to use in filtering. The default locale is the host environment's current locale. |
selection | any | null | Selected row in single mode or an array of values in multiple mode. |
selectionMode | string | null | Specifies the selection mode, valid values are "single" and "multiple". |
compareSelectionBy | string | deepEquals |
Algorithm to define if a row is selected, valid values are "equals" that compares by reference and "deepEquals" that compares all fields. |
metaKeySelection | boolean | true |
Defines whether metaKey is requred or not for the selection. When true metaKey needs to be pressed to select or unselect an item and when set to false selection of each item can be toggled individually. On touch enabled devices, metaKeySelection is turned off automatically. |
contextMenu | boolean | false | Enables context menu integration. |
contextMenuSelection | object | null | Selected row instance with the ContextMenu. |
rowHover | boolean | false | When enabled, background of the rows change on hover. |
csvSeparator | string | , | Character to use as the csv separator. |
exportFilename | string | download | Name of the exported file. |
exportFunction | function | download | Custom function to export data. |
autoLayout | boolean | false | Whether the cell widths scale according to their content or not. Does not apply to scrollable tables. |
resizableColumns | boolean | false | When enabled, columns can be resized using drag and drop. |
columnResizeMode | string | fit |
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. |
expandedRows | array | null | A collection of row data display as expanded. |
expandedRowIcon | string | pi-chevron-down | Icon of the row toggler to display the row as expanded. |
collapsedRowIcon | string | pi-chevron-right | Icon of the row toggler to display the row as collapsed. |
rowGroupMode | string | null | Defines the row group mode, valid options are "subheader" and "rowspan". |
groupRowsBy | string|array | null | One or more field names to use in row grouping. |
expandableRowGroups | boolean | false | Whether the row groups can be expandable. |
expandedRowGroups | array | null | An array of group field values whose groups would be rendered as expanded. |
stateStorage | string | session | Defines where a stateful table keeps its state, valid values are "session" for sessionStorage and "local" for localStorage. |
stateKey | string | null | Unique identifier of a stateful table to use in state storage. |
editMode | string | null | Defines the incell editing mode, valid options are "cell" and "row". |
editingRows | array | null | A collection of rows to represent the current editing data in row edit mode. |
rowClass | function | null | A function that takes the row data as a parameter and returns a string to apply a particular class for the row. |
rowStyle | object | null | Inline style of the row element. |
scrollable | boolean | false | When specified, enables horizontal and/or vertical scrolling. |
scrollDirection | string | vertical | Orientation of the scrolling, options are "vertical", "horizontal" and "both". |
scrollHeight | string | null | Height of the scroll viewport in fixed pixels or the "flex" keyword for a dynamic size. |
virtualScrollerOptions | object | null |
Whether to use the virtualScroller feature. The properties of Note: Currently only vertical orientation mode is supported. |
frozenValue | array | null | Items of the frozen part in scrollable DataTable. |
responsiveLayout | string | stack | Defines the responsive mode, valid options are "stack" and "scroll". |
breakpoint | string | 960px | The breakpoint to define the maximum width boundary when using stack responsive layout. |
showGridlines | boolean | false | Whether to show grid lines between cells. |
stripedRows | boolean | false | Whether to displays rows with alternating colors. |
tableStyle | object | null | Inline style of the table element. |
tableClass | string | null | Style class of the table element. |
tableProps | object | null | Uses to pass all properties of the TableHTMLAttributes to table element inside the component. |
filterInputProps | object | null | Uses to pass all properties of the HTMLInputElement to the focusable filter input element inside the component. |
Name | Parameters | Description |
---|---|---|
page |
event.originalEvent: Browser event event.page: New page number event.pageCount: Total page count event.first: Index of first record event.rows: Number of rows to display in new page event.sortField: Field to sort against event.sortOrder: Sort order as integer event.multiSortMeta: MultiSort metadata event.filters: Collection of active filters event.filterMatchModes: Match modes per field |
Callback to invoke on pagination. Sort and Filter information is also available for lazy loading implementation. |
sort |
event.originalEvent: Browser event event.first: Index of first record event.rows: Number of rows to display in new page event.sortField: Field to sort against event.sortOrder: Sort order as integer event.multiSortMeta: MultiSort metadata event.filters: Collection of active filters event.filterMatchModes: Match modes per field |
Callback to invoke on sort. Page and Filter information is also available for lazy loading implementation. |
filter |
event.originalEvent: Browser event event.first: Index of first record event.rows: Number of rows to display in new page event.sortField: Field to sort against event.sortOrder: Sort order as integer event.multiSortMeta: MultiSort metadata event.filters: Collection of active filters event.filteredValue: Filtered collection (non-lazy only) |
Event to emit after filtering, not triggered in lazy mode. |
value-change | value: Value displayed by the table | Callback to invoke after filtering, sorting, pagination and cell editing to pass the rendered value. |
row-click |
event.originalEvent: Browser event. event.data: Selected row data. event.index: Row index. |
Callback to invoke when a row is clicked. |
row-dblclick |
event.originalEvent: Browser event. event.data: Selected row data. event.index: Row index. |
Callback to invoke when a row is double clicked. |
row-contextmenu |
event.originalEvent: Browser event. event.data: Selected row data. event.index: Row index. |
Callback to invoke when a row is selected with a ContextMenu. |
row-select |
event.originalEvent: Browser event. event.data: Selected row data. event.index: Row index. event.type: Type of the selection, valid values are "row", "radio" or "checkbox". |
Callback to invoke when a row is selected. |
row-unselect |
event.originalEvent: Browser event. event.data: Unselected row data. event.index: Row index. event.type: Type of the selection, valid values are "row", "radio" or "checkbox". |
Callback to invoke when a row is unselected. |
row-select-all |
event.originalEvent: Browser event. event.data: Selected dataset |
Fired when header checkbox is checked. |
row-unselect-all | event.originalEvent: Browser event. | Fired when header checkbox is unchecked. |
column-resize-end |
event.element: DOM element of the resized column. event.delta: Change in column width |
Callback to invoke when a column is resized. |
column-reorder |
event.originalEvent: Browser event event.dragIndex: Index of the dragged column event.dropIndex: Index of the dropped column |
Callback to invoke when a column is reordered. |
row-reorder |
event.originalEvent: Browser event event.dragIndex: Index of the dragged row event.dropIndex: Index of the dropped row value: Reordered value |
Callback to invoke when a row is reordered. |
row-expand |
event.originalEvent: Browser event event.data: Expanded row data. |
Callback to invoke when a row is expanded. |
row-collapse |
event.originalEvent: Browser event event.data: Collapsed row data. |
Callback to invoke when a row is collapsed. |
rowgroup-expand |
event.originalEvent: Browser event event.data: Expanded group value. |
Callback to invoke when a row group is expanded. |
rowgroup-collapse |
event.originalEvent: Browser event event.data: Collapsed group value. |
Callback to invoke when a row group is collapsed. |
cell-edit-init |
event.originalEvent: Browser event event.data: Row data to edit. event.field: Field name of the row data. event.index: Index of the row data to edit. |
Callback to invoke when cell edit is initiated. |
cell-edit-complete |
event.originalEvent: Browser event event.data: Row data to edit. event.newData: New row data after editing. event.value: Field value of row data to edit. event.newValue: Field value of new row data after editing. event.field: Field name of the row data. event.index: Index of the row data to edit. event.type: Type of completion such as "enter", "outside" or "tab". |
Callback to invoke when cell edit is completed. |
cell-edit-cancel |
event.originalEvent: Browser event event.data: Row data to edit. event.field: Field name of the row data. event.index: Index of the row data to edit. |
Callback to invoke when cell edit is cancelled with escape key. |
row-edit-init |
event.originalEvent: Browser event event.data: Row data to edit. event.newData: New row data after editing. event.field: Field name of the row data. event.index: Index of the row data to edit. |
Callback to invoke when row edit is initiated. |
row-edit-save |
event.originalEvent: Browser event event.data: Row data to edit. event.newData: New row data after editing. event.field: Field name of the row data. event.index: Index of the row data to edit. |
Callback to invoke when row edit is saved. |
row-edit-cancel |
event.originalEvent: Browser event event.data: Row data to edit. event.newData: New row data after editing. event.field: Field name of the row data. event.index: Index of the row data to edit. |
Callback to invoke when row edit is cancelled. |
state-save |
event.first: Index of first record event.rows: Number of rows to display in new page event.sortField: Field to sort against event.sortOrder: Sort order as integer event.multiSortMeta: MultiSort metadata event.filters: Collection of active filters event.columWidths: Comma separated list of column widths event.columnOrder: Order of the columns event.expandedRows: Instances of rows in expanded state event.expandedRowKeys: Keys of rows in expanded state event.expandedRowGroups: Instances of row groups in expanded state event.selection: Selected rows event.selectionKeys: Keys of selected rows |
Invoked when a stateful table saves the state. |
state-restore |
event.first: Index of first record event.rows: Number of rows to display in new page event.sortField: Field to sort against event.sortOrder: Sort order as integer event.multiSortMeta: MultiSort metadata event.filters: Collection of active filters event.columWidths: Comma separated list of column widths event.columnOrder: Order of the columns event.expandedRows: Instances of rows in expanded state event.expandedRowKeys: Keys of rows in expanded state event.expandedRowGroups: Instances of row groups in expanded state event.selection: Selected rows event.selectionKeys: Keys of selected rows |
Invoked when a stateful table restores the state. |
Name | Parameters | Description |
---|---|---|
exportCSV | - | Exports the data to CSV format. |
Name | Parameters |
---|---|
header | column: Column node |
paginatorstart | - |
paginatorend | - |
footer | column: Column node |
groupheader |
data: Row data index: Row index |
groupfooter |
data: Row data index: Row index |
expansion |
data: Row data index: Row index |
empty | - |
loading | - |
Any property as style and class are passed to the main container element. Following are the additional properties to configure the component.
Name | Element |
---|---|
p-datatable | Container element. |
p-datatable-scrollable | Container element when table is scrollable. |
p-datatable-header | Header section. |
p-datatable-footer | Footer section. |
p-datatable-wrapper | Wrapper of table element. |
p-datatable-table | Table element. |
p-datatable-thead | Table thead element. |
p-datatable-tbody | Table tbody element. |
p-datatable-tfoot | Table tfoot element. |
p-column-title | Title of a column. |
p-sortable-column | Sortable column header. |
p-frozen-column | Frozen column header. |
p-rowgroup-header | Header of a rowgroup. |
p-rowgroup-footer | Footer of a rowgroup. |
p-datatable-row-expansion | Expanded row content. |
p-row-toggler | Toggle element for row expansion. |
p-datatable-emptymessage | Cell containing the empty message. |
p-row-editor-init | Pencil button of row editor. |
p-row-editor-init | Save button of row editor. |
p-row-editor-init | Cancel button of row editor. |
DataTable uses a table element whose attributes can be extended with the tableProps option. This property allows passing aria roles and attributes like aria-label and aria-describedby to define the table for readers. Default role of the table is table. Header, body and footer elements use rowgroup, rows use row role, header cells have columnheader and body cells use cell roles. Sortable headers utilizer aria-sort attribute either set to "ascending" or "descending".
Built-in checkbox and radiobutton components for row selection use checkbox and radiobutton. The label to describe them is retrieved from the aria.selectRow and aria.unselectRow properties of the
The element to expand or collapse a row is a button with aria-expanded and aria-controls properties. Value to describe the buttons is derived from aria.expandRow and aria.collapseRow properties of
the
The filter menu button use aria.showFilterMenu and aria.hideFilterMenu properties as aria-label in addition to the aria-haspopup, aria-expanded and aria-controls to define the relation between the button and the overlay. Popop menu has dialog role with aria-modal as focus is kept within the overlay. The operator dropdown use aria.filterOperator and filter constraints dropdown use aria.filterConstraint properties. Buttons to add rules on the other hand utilize aria.addRule and aria.removeRule properties. The footer buttons similarly use aria.clear and aria.apply properties. filterInputProps of the Column component can be used to define aria labels for the built-in filter components, if a custom component is used with templating you also may define your own aria labels as well.
Editable cells use custom templating so you need to manage aria roles and attributes manually if required. The row editor controls are button elements with aria.editRow, aria.cancelEdit and aria.saveEdit used for the aria-label.
Paginator is a standalone component used inside the DataTable, refer to the
Any button element inside the DataTable used for cases like filter, row expansion, edit are tabbable and can be used with space and enter keys.
Key | Function |
---|---|
tab | Moves through the headers. |
enter | Sorts the column. |
space | Sorts the column. |
Key | Function |
---|---|
tab | Moves through the elements inside the popup. |
escape | Hides the popup. |
Key | Function |
---|---|
tab | Moves focus to the first selected row, if there is none then first row receives the focus. |
up arrow | Moves focus to the previous row. |
down arrow | Moves focus to the next row. |
enter | Toggles the selected state of the focused row depending on the metaKeySelection setting. |
space | Toggles the selected state of the focused row depending on the metaKeySelection setting. |
home | Moves focus to the first row. |
end | Moves focus to the last row. |
shift + down arrow | Moves focus to the next row and toggles the selection state. |
shift + up arrow | Moves focus to the previous row and toggles the selection state. |
shift + space | Selects the rows between the most recently selected row and the focused row. |
control + shift + home | Selects the focused rows and all the options up to the first one. |
control + shift + end | Selects the focused rows and all the options down to the last one. |
control + a | Selects all rows. |
None.