- Change Detection
- Sections
- Column Grouping
- Row Grouping
- Multi Field grouping
- Paginator
- Sorting
- Filtering
- Selection
- ContextMenu
- Cell Editing
- Row Editing
- Expandable Rows
- Column Resize
- Column Reordering
- Rows Reordering
- Data Export
- Scrolling
- Lazy Loading
- TableState
- Responsive
- EmptyMessage
- Loading Status
- Styling Certain Rows and Columns
- Performance Tips
- Properties
- Events
- Methods
- Styling
- Dependencies
- Source
- ● Documentation
- ● Sections
- ● Page
- ● Sort
- ● Selection
- ● Filter
- ● ColGroup
- ● Lazy
- ● Edit
- ● Scroll
- ● RowExpand
- ● RowGroup
- ● Resize
- ● Reorder
- ● Toggle
- ● Style
- ● Export
- ● ContextMenu
- ● Responsive
- ● Crud
- ● State
- ● Sticky
TurboTableTable is the successor of p-dataTable with a lightning fast performance (at least 10x faster) and excellent level of control over the presentation. p-table is called as TurboTable in order to differantiate if from the deprecated p-dataTable.
## Documentation
### Import
import {TableModule} from 'primeng/table';
### Getting Started
Table requires a value as an array of objects and templates for the presentation. Throughout the samples, a car interface having vin, brand, year and color properties is used to define an object to be displayed by the table. Cars are loaded by a CarService that connects to a server to fetch the data.
export interface Car {
vin;
year;
brand;
color;
}
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Car } from '../domain/car';
@Injectable()
export class CarService {
constructor(private http: HttpClient) {}
getCarsSmall() {
return this.http.get('/showcase/resources/data/cars-small.json')
.toPromise()
.then(res => <Car[]> res.data)
.then(data => { return data; });
}
}
Following sample has a table of 4 columns and retrieves the data from a service on ngOnInit.
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 whereas header and body templates are used to define the content of these sections.
<p-table [value]="cars">
<ng-template pTemplate="header">
<tr>
<th>Vin</th>
<th>Year</th>
<th>Brand</th>
<th>Color</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-car>
<tr>
<td>{{car.vin}}</td>
<td>{{car.year}}</td>
<td>{{car.brand}}</td>
<td>{{car.color}}</td>
</tr>
</ng-template>
</p-table>
### Dynamic Columns
Instead of configuring columns one by one, a simple ngFor can be used to implement dynamic columns. cols property below is an array of objects that represent a column, only property that table component uses is field, rest of the properties like header depend on your choice.
export class DynamicColumnsDemo 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' }
];
}
}
There are two ways to render dynamic columns, since cols property is in the scope of component you can just simply bind it to ngFor directive to generate the structure.
<p-table [value]="cars">
<ng-template pTemplate="header">
<tr>
<th ngFor="let col of cols">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-car>
<tr>
<td ngFor="let col of cols">
{{car[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
Other alternative is binding the cols array to the columns property and then defining a template variable to access it within your templates. There are 3 cases where this is required which are csv export, reorderable columns and global filtering without the globalFilterFields property.
<p-table [columns]="cols" [value]="cars">
<ng-template pTemplate="header" let-columns>
<tr>
<th ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-car let-columns="columns">
<tr>
<td ngFor="let col of columns">
{{car[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
Tip: Use ngSwitch to customize the column content per dynamic column.
### Table Layout
For performance reasons, 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 reasons.
### Templates
Table is a template driven component with named templates such as header and body that we've used so far. Templates grant a great level of customization and flexibility where you have total control over the presentation while table handles the features such as paging, sorting, filtering and more. This speeds up development without sacrifing flexibility. Here is the full list of available templates.
Name | Parameters | Description |
---|---|---|
caption | - | Caption content of the table. |
header | $implicit: Columns | Content of the thead element. |
body | $implicit: Data of the row rowIndex: Index of the row columns: Columns collection expanded: Whether the row is expanded | Content of the tbody element. |
footer | $implicit: Columns | Content of the tfoot element. |
summary | - | Summary section to display below the table. |
colgroup | $implicit: Columns | ColGroup element of the table to customize columns. |
rowexpansion | $implicit: Data of the row rowIndex: Index of the row columns: Columns collection | Content of an extended row. |
frozenrows | $implicit: Data of the row rowIndex: Index of the row columns: Columns collection | Content of the tbody element to display frozen rows. |
frozenheader | $implicit: Columns | Content of the thead element in frozen side. |
frozenbody | $implicit: Data of the row rowIndex: Index of the row columns: Columns collection | Content of the tbody element in frozen side. |
frozenfooter | $implicit: Columns | Content of the tfoot element in frozen side. |
frozencolgroup | $implicit: Columns | ColGroup element of the table to customize frozen columns. |
emptymessage | $implicit: Columns | Content to display when there is no value to display. |
paginatorleft | state: $implicit state.page: Current page state.pageCount: Total page count state.rows: Rows per page state.first: Index of the first records state.totalRecords: Number of total records | Custom content for the left section of the paginator. |
paginatorright | state: $implicit state.page: Current page state.pageCount: Total page count state.rows: Rows per page state.first: Index of the first records state.totalRecords: Number of total records | Custom content for the right section of the paginator. |
loadingbody | columns: Columns collection | Content of the tbody element to show when data is being loaded in virtual scroll mode. |
Change Detection
Table may need to be aware of changes in its value in some cases such as reapplying sort. For the sake of performance, this is only done when the reference of the value changes meaning a setter is used instead of ngDoCheck/IterableDiffers which can reduce performance. So when you manipulate the value such as removing or adding an item, instead of using array methods such as push, splice create a new array reference using a spread operator or similar.
Sections
Table offers various templates to display additional information about the data such as a caption or summary.
<p-table [columns]="cols" [value]="cars">
<ng-template pTemplate="caption">
List of Cars
</ng-template>
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
<ng-template pTemplate="footer" let-columns>
<tr>
<td *ngFor="let col of columns">
{{col.header}}
</td>
</tr>
</ng-template>
<ng-template pTemplate="summary">
There are {{cars?.length}} cars
</ng-template>
</p-table>
See the live example.
Column Grouping
Columns can easily be grouped using templating. Let's start with sample data of sales of brands per year.
export class TableColGroupDemo implements OnInit {
sales: any[];
ngOnInit() {
this.sales = [
{ brand: 'Apple', lastYearSale: '51%', thisYearSale: '40%', lastYearProfit: '$54,406.00', thisYearProfit: '$43,342' },
{ brand: 'Samsung', lastYearSale: '83%', thisYearSale: '96%', lastYearProfit: '$423,132', thisYearProfit: '$312,122' },
{ brand: 'Microsoft', lastYearSale: '38%', thisYearSale: '5%', lastYearProfit: '$12,321', thisYearProfit: '$8,500' },
{ brand: 'Philips', lastYearSale: '49%', thisYearSale: '22%', lastYearProfit: '$745,232', thisYearProfit: '$650,323,' },
{ brand: 'Song', lastYearSale: '17%', thisYearSale: '79%', lastYearProfit: '$643,242', thisYearProfit: '500,332' },
{ brand: 'LG', lastYearSale: '52%', thisYearSale: ' 65%', lastYearProfit: '$421,132', thisYearProfit: '$150,005' },
{ brand: 'Sharp', lastYearSale: '82%', thisYearSale: '12%', lastYearProfit: '$131,211', thisYearProfit: '$100,214' },
{ brand: 'Panasonic', lastYearSale: '44%', thisYearSale: '45%', lastYearProfit: '$66,442', thisYearProfit: '$53,322' },
{ brand: 'HTC', lastYearSale: '90%', thisYearSale: '56%', lastYearProfit: '$765,442', thisYearProfit: '$296,232' },
{ brand: 'Toshiba', lastYearSale: '75%', thisYearSale: '54%', lastYearProfit: '$21,212', thisYearProfit: '$12,533' }
];
}
}
<p-table [value]="sales">
<ng-template pTemplate="header">
<tr>
<th rowspan="3">Brand</th>
<th colspan="4">Sale Rate</th>
</tr>
<tr>
<th colspan="2">Sales</th>
<th colspan="2">Profits</th>
</tr>
<tr>
<th>Last Year</th>
<th>This Year</th>
<th>Last Year</th>
<th>This Year</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-sale>
<tr>
<td>{{sale.brand}}</td>
<td>{{sale.lastYearSale}}</td>
<td>{{sale.thisYearSale}}</td>
<td>{{sale.lastYearProfit}}</td>
<td>{{sale.thisYearProfit}}</td>
</tr>
</ng-template>
<ng-template pTemplate="footer">
<tr>
<td colspan="3">Totals</td>
<td>$506,202</td>
<td>$531,020</td>
</tr>
</ng-template>
</p-table>
See the live example.
Row Grouping
Templating features can also be used to implement row grouping functionality, here is an example implementation that uses a metadata object to keep at what index a group starts and how many items it has.
export class TableRowGroupDemo implements OnInit {
cars: Car[];
rowGroupMetadata: any;
constructor(private carService: CarService) { }
ngOnInit() {
this.carService.getCarsMedium().then(cars => {
this.cars = cars;
this.updateRowGroupMetaData();
});
}
onSort() {
this.updateRowGroupMetaData();
}
updateRowGroupMetaData() {
this.rowGroupMetadata = {};
if (this.cars) {
for (let i = 0; i < this.cars.length; i++) {
let rowData = this.cars[i];
let brand = rowData.brand;
if (i == 0) {
this.rowGroupMetadata[brand] = { index: 0, size: 1 };
}
else {
let previousRowData = this.cars[i - 1];
let previousRowGroup = previousRowData.brand;
if (brand === previousRowGroup)
this.rowGroupMetadata[brand].size++;
else
this.rowGroupMetadata[brand] = { index: i, size: 1 };
}
}
}
}
}
Using this metadata rows can be grouped using a subheader that displays the group. Note that grouped data should be sorted so enable sortField so that table applies sorting before grouping if your data is not sorted.
<p-table [value]="cars" sortField="brand" sortMode="single" (onSort)="onSort()">
<ng-template pTemplate="header">
<tr>
<th>Vin</th>
<th>Year</th>
<th>Color</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex">
<tr class="ui-widget-header" *ngIf="rowGroupMetadata[rowData.brand].index === rowIndex">
<td colspan="3">
<span style="font-weight:bold">{{rowData.brand}}</span>
</td>
</tr>
<tr>
<td>{{rowData.vin}}</td>
<td>{{rowData.year}}</td>
<td>{{rowData.color}}</td>
</tr>
</ng-template>
</p-table>
An alternative grouping could be using rowspans for the group field.
<p-table [value]="cars" sortField="brand" sortMode="single" (onSort)="onSort()">
<ng-template pTemplate="header">
<tr>
<th>Brand</th>
<th>Vin</th>
<th>Year</th>
<th>Color</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex">
<tr>
<td *ngIf="rowGroupMetadata[rowData.brand].index === rowIndex" [attr.rowspan]="rowGroupMetadata[rowData.brand].size">
{{rowData.brand}}
</td>
<td>{{rowData.vin}}</td>
<td>{{rowData.year}}</td>
<td>{{rowData.color}}</td>
</tr>
</ng-template>
</p-table>
See the live example.
Multi Field grouping
Previous example uses a single field to group the rows however nothing limits you to implement multiple field grouping as well. Similarly to single grouping, your data should be sorted first, you may use the built-in multiSorting or provide it sorted to the table and create a rowGroupMetadata for multiple fields.
Paginator
Pagination is enabled by setting paginator property to true, rows property 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-table [columns]="cols" [value]="cars" [paginator]="true" [rows]="10">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
Paginator can also be controlled via model using a binding to the first property where changes trigger a pagination.
<p-table [columns]="cols" [value]="cars" [paginator]="true" [rows]="10" [first]="first">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
export class DataTablePageDemo implements OnInit {
cars: Car[];
first: number = 0;
constructor(private carService: CarService) { }
ngOnInit() {
this.carService.getCarsSmall().then(cars => this.cars = cars);
}
reset() {
this.first = 0;
}
}
Paginator accepts custom content for the left and the right side via named templates.
<p-table [columns]="cols" [value]="cars" [paginator]="true" [rows]="10" [first]="first">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
<ng-template pTemplate="paginatorleft" let-state>
{{state.first}}
<button type="button" pButton icon="fa-refresh"></button>
</ng-template>
<ng-template pTemplate="paginatorright">
<button type="button" pButton icon="fa-cloud-upload"></button>
</ng-template>
</p-table>
Paginator templates gets the paginator state as an implicit variable that provides the following properties
- first
- rows
- page
- totalRecords
See the live example.
Sorting
A column can be made sortable by adding the pSortableColumn directive whose value is the field to sort against and a sort indicator via p-sortIcon component. For dynamic columns, setting pSortableColumnDisabled property as true disables sorting for that particular column.
<p-table [columns]="cols" [value]="cars1">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns" [pSortableColumn]="col.field">
{{col.header}}
<p-sortIcon [field]="col.field"></p-sortIcon>
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
Default sorting is executed on a single column, in order to enable multiple field sorting, set sortMode property to "multiple" and use metakey when clicking on another column.
<p-table [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-table [columns]="cols" [value]="cars1" sortField="year">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns" [pSortableColumn]="col.field">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
In multiple mode, use the multiSortMeta property and bind an array of SortMeta objects.
<p-table [columns]="cols" [value]="cars1" sortMode="multiple" [multiSortMeta]="multiSortMeta">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns" [pSortableColumn]="col.field">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
this.multiSortMeta = [];
this.multiSortMeta.push({field: 'year', order: 1});
this.multiSortMeta.push({field: 'brand', order: -1});
Instead of using the built-in sorting algorithm a custom sort can be attached by enabling customSort property and defining a sortFunction implementation. This function gets a SortEvent instance that provides the data to sort, sortField, sortOrder and multiSortMeta.
export class CustomTableSortDemo implements OnInit {
cars: Car[];
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' }
];
}
customSort(event: SortEvent) {
//event.data = Data to sort
//event.mode = 'single' or 'multiple' sort mode
//event.field = Sort field in single sort
//event.order = Sort order in single sort
//event.multiSortMeta = SortMeta array in multiple sort
event.data.sort((data1, data2) => {
let value1 = data1[event.field];
let value2 = data2[event.field];
let result = null;
if (value1 == null && value2 != null)
result = -1;
else if (value1 != null && value2 == null)
result = 1;
else if (value1 == null && value2 == null)
result = 0;
else if (typeof value1 === 'string' && typeof value2 === 'string')
result = value1.localeCompare(value2);
else
result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0;
return (event.order * result);
});
}
}
<p-table [columns]="cols" [value]="cars" (sortFunction)="customSort($event)" [customSort]="true">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns" [pSortableColumn]="col.field">
{{col.header}}
<p-sortIcon [field]="col.field"></p-sortIcon>
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
For screen reader support of sortable headers, use ariaLabel, ariaLabelDesc and ariaLabelAsc properties on p-sortIcon component to define aria labels for unsorted, descending and ascending states respectively.
See the live example.
Filtering
Filtering is enabled by defining the filter and calling filter method on the local template variable of the table with value, column field and match mode parameters. Available match modes are "startsWith", "contains", "endsWith", "equals", "notEquals", "in", "lt", "lte", "gt" and "gte". Following is an example that utilizes various PrimeNG form components as filters.
An optional global filter feature is available to search all fields with the same query, to enable this place an input component and call the filterGlobal function with value and match mode properties on your event of choice.
<p-table #tt [columns]="cols" [value]="cars" [paginator]="true" [rows]="10">
<ng-template pTemplate="caption">
<i class="fa fa-search" style="margin:4px 4px 0 0"></i>
<input type="text" pInputText size="50" placeholder="Global Filter" (input)="tt.filterGlobal($event.target.value, 'contains')" style="width:auto">
</ng-template>
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
<tr>
<th *ngFor="let col of columns" [ngSwitch]="col.field">
<input *ngSwitchCase="'vin'" pInputText type="text" (input)="tt.filter($event.target.value, col.field, col.filterMatchMode)">
<div *ngSwitchCase="'year'">
{{yearFilter}}
<i class="fa fa-close" (click)="yearFilter=null;tt.filter(null, col.field, col.filterMatchMode)"></i>
<p-slider [style]="{'width':'100%','margin-top':'8px'}" [(ngModel)]="yearFilter" [min]="1970" [max]="2010" (onChange)="onYearChange($event, dt)"></p-slider>
</div>
<p-dropdown *ngSwitchCase="'brand'" [options]="brands" [style]="{'width':'100%'}" (onChange)="tt.filter($event.value, col.field, 'equals')"></p-dropdown>
<p-multiSelect *ngSwitchCase="'color'" [options]="colors" defaultLabel="All Colors" (onChange)="tt.filter($event.value, col.field, 'in')"></p-multiSelect>
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr [pSelectableRow]="rowData">
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
export class TableFilterDemo implements OnInit {
cars: Car[];
cols: any[];
brands: SelectItem[];
colors: SelectItem[];
yearFilter: number;
yearTimeout: any;
constructor(private carService: CarService) { }
ngOnInit() {
this.carService.getCarsMedium().then(cars => this.cars = cars);
this.brands = [
{ label: 'All Brands', value: null },
{ label: 'Audi', value: 'Audi' },
{ label: 'BMW', value: 'BMW' },
{ label: 'Fiat', value: 'Fiat' },
{ label: 'Honda', value: 'Honda' },
{ label: 'Jaguar', value: 'Jaguar' },
{ label: 'Mercedes', value: 'Mercedes' },
{ label: 'Renault', value: 'Renault' },
{ label: 'VW', value: 'VW' },
{ label: 'Volvo', value: 'Volvo' }
];
this.colors = [
{ label: 'White', value: 'White' },
{ label: 'Green', value: 'Green' },
{ label: 'Silver', value: 'Silver' },
{ label: 'Black', value: 'Black' },
{ label: 'Red', value: 'Red' },
{ label: 'Maroon', value: 'Maroon' },
{ label: 'Brown', value: 'Brown' },
{ label: 'Orange', value: 'Orange' },
{ label: 'Blue', value: 'Blue' }
];
this.cols = [
{ field: 'vin', header: 'Vin' },
{ field: 'year', header: 'Year' },
{ field: 'brand', header: 'Brand' },
{ field: 'color', header: 'Color' }
];
}
onYearChange(event, dt) {
if (this.yearTimeout) {
clearTimeout(this.yearTimeout);
}
this.yearTimeout = setTimeout(() => {
tt.filter(event.value, 'year', 'gt');
}, 250);
}
}
If you have static columns and need to use global filtering, globalFilterFields property must be defined to configure which fields should be used in global filtering. Another use case of this property is to change the fields to utilize in global filtering with dynamic columns.
<p-table [value]="cars" [paginator]="true" [rows]="10" [globalFilterFields]="['vin','year']">
//content
</p-table>
See the live example.
Selection
Table provides built-in single and multiple selection features where selected rows are bound to the selection property and onRowSelect-onRowUnselect events are provided as optional callbacks. In order to enable this feature, define a selectionMode, bind a selection reference and add pSelectableRow directive whose value is the rowData to the rows that can be selected. Additionally if you prefer double click use pSelectableRowDblClick directive instead and to disable selection events on a particular row use pSelectableRowDisabled. In both cases optional pSelectableRowIndex property is avaiable to access the row index. By default each row click adds or removes the row from the selection, if you prefer a classic metaKey based selection approach enable metaKeySelection true so that multiple selection or unselection of a row requires metaKey to be pressed. Note that, on touch enabled devices, metaKey based selection is turned off automatically as there is no metaKey in devices such as mobile phones.
Alternative to the row click, radiobutton or checkbox elements can be used to implement row selection.
When resolving if a row is selected, by default Table compares selection array with the datasource which may cause a performance issue with huge datasets that do not use pagination. If available the fastest way is to use dataKey property that identifies a unique row so that Table can avoid comparing arrays as internally a map instance is used instead of looping arrays, on the other hand if dataKey cannot be provided consider using compareSelectionBy property as "equals" which uses reference comparison instead of the default "deepEquals" comparison. Latter is slower since it checks all properties.
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-table [columns]="cols" [value]="cars" selectionMode="single" [(selection)]="selectedCar">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr [pSelectableRow]="rowData">
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
In multiple mode, selection binding should be an array. Note that if you require shiftKey based range selection, pass the rowIndex to the SelectableRow directive.
export class DataTableDemo implements OnInit {
cars: Car[];
selectedCars: Car[];
constructor(private carService: CarService) { }
ngOnInit() {
this.carService.getCarsSmall().then(cars => this.cars = cars);
}
}
<p-table [columns]="cols" [value]="cars" selectionMode="multiple" [(selection)]="selectedCars">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns" let-rowIndex="rowIndex">
<tr [pSelectableRow]="rowData" [pSelectableRowIndex]="rowIndex">
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
Single selection using a radiobutton can be done by using p-tableRadioButton component.
<p-table [columns]="cols" [value]="cars" [(selection)]="selectedCar" dataKey="vin">
<ng-template pTemplate="header" let-columns>
<tr>
<th style="width: 2.25em"></th>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td>
<p-tableRadioButton [value]="rowData"></p-tableRadioButton>
</td>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
<ng-template pTemplate="summary">
<div style="text-align: left">
Selected Car: {{selectedCar4 ? selectedCar4.vin + ' - ' + selectedCar4.brand + ' - ' + selectedCar4.year + ' - ' + selectedCar4.color: 'none'}}
</div>
</ng-template>
</p-table>
Similarly p-tableCheckbox and p-tableHeaderCheckbox elements are provide to implement checkbox based multiple selection.
<p-table [columns]="cols" [value]="cars" [(selection)]="selectedCars" dataKey="vin">
<ng-template pTemplate="header" let-columns>
<tr>
<th style="width: 2.25em">
<p-tableHeaderCheckbox></p-tableHeaderCheckbox>
</th>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td>
<p-tableCheckbox [value]="rowData"></p-tableCheckbox>
</td>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
Both p-tableCheckbox and p-tableRadioButton components can be disabled using their property with the same name to prevent selection of a particular row. In addition, index of the row needs to be provided to the checkbox/radiobutton components so that they can be available at the onRowSelect or onRowUnselect events of the Table.
<ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex" let-columns="columns">
<tr [pSelectableRow]="rowData">
<td>
<p-tableCheckbox [value]="rowData" [disabled]="rowData.year > 2010" [index]="rowIndex"></p-tableCheckbox>
</td>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
See the live example.
ContextMenu
DataTable has exclusive integration with contextmenu component. In order to attach a menu to a datatable, add pContextMenuRow directive to the rows that can be selected with context menu, define a local template variable for the menu and bind it to the contextMenu property of the datatable. This enables displaying the menu whenever a row is right clicked. Optional pContextMenuRowIndex property is avaiable to access the row index. A separate contextMenuSelection property is used to get a hold of the right clicked row. For dynamic columns, setting pContextMenuRowDisabled property as true disables context menu for that particular row.
<p-table [columns]="cols" [value]="cars" [(contextMenuSelection)]="selectedCar" [contextMenu]="cm">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns" let-rowIndex="rowIndex">
<tr [pContextMenuRow]="rowData" [pContextMenuRowIndex]="rowIndex">
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
<p-contextMenu #cm [model]="items"></p-contextMenu>
By default context menu uses a different property called contextMenuSelection as above, this means when row selection mode is also enabled, the two properties, both selection and contextMenuSelection need to be maintained. In case you prefer to configure Table to manage the same selection property both on row click and context menu, set contextMenuSelectionMode as "joint". Table below has both selectionMode and contextMenu enabled where both of these features update the same selection object.
<p-table [columns]="cols" [value]="cars" selectionMode="single" [(selection)]="selectedCar" [contextMenu]="cm" contextMenuSelectionMode="joint">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr [pSelectableRow]="rowData" [pContextMenuRow]="rowData">
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
<p-contextMenu #cm [model]="items"></p-contextMenu>
See the live example.
Cell Editing
Incell editing is enabled by adding pEditableColumn directive to an editable cell that has a p:cellEditor helper component to define the input-output templates for the edit and view modes respectively.
<p-table [columns]="cols" [value]="cars">
<ng-template pTemplate="header" let-columns>
<tr>
<th>Vin</th>
<th>Year</th>
<th>Brand</th>
<th>Color</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td pEditableColumn>
<p-cellEditor>
<ng-template pTemplate="input">
<input type="text" [(ngModel)]="rowData.vin">
</ng-template>
<ng-template pTemplate="output">
{{rowData.vin}}
</ng-template>
</p-cellEditor>
</td>
<td pEditableColumn>
<p-cellEditor>
<ng-template pTemplate="input">
<input type="text" [(ngModel)]="rowData.year" required>
</ng-template>
<ng-template pTemplate="output">
{{rowData.year}}
</ng-template>
</p-cellEditor>
</td>
<td pEditableColumn>
<p-cellEditor>
<ng-template pTemplate="input">
<input type="text" [(ngModel)]="rowData.brand">
</ng-template>
<ng-template pTemplate="output">
{{rowData.brand}}
</ng-template>
</p-cellEditor>
</td>
<td pEditableColumn>
<p-cellEditor>
<ng-template pTemplate="input">
<input type="text" [(ngModel)]="rowData.color">
</ng-template>
<ng-template pTemplate="output">
{{rowData.color}}
</ng-template>
</p-cellEditor>
</td>
</tr>
</ng-template>
</p-table>
If you require the edited row data or the selected field in the onEditInit, onEditComplete, and onEditCancel events, bind the row data to the pEditableColumn directive and the field to the pEditableColumnField directive.
<td [pEditableColumn]="rowData" [pEditableColumnField]="'year'">
When opening a cell for editing, the table will automatically focus the first input, textarea, or select element inside the output template. If you want to override this default behavior, you can pass a custom selector for the elements to focus into the pFocusCellSelector directive. This is useful when you would like the Tab and Shift+Tab keyboard navigation to focus on buttons or custom edit controls.
<td [pFocusCellSelector]="'input, .custom-edit-control'">
Row Editing
Row editing toggles the visibility of the all editors in the row at once and provides additional options to save and cancel editing. Row editing functionality is enabled by setting the to "row" on table, defining a dataKey to uniquely identify a row, adding pEditableRow directive to the editable rows and defining the UI Controls with pInitEditableRow, pSaveEditableRow and pCancelEditableRow directives respectively.
Save and Cancel functionality implementation is left to the page author to provide more control over the editing business logic, example below utilizes a simple implementation where a row is cloned when editing is initialized and is saved or restored depending on the result of the editing. An implicit variable called "editing" is passed to the body template so you may come up with your own UI controls that implement editing based on your own requirements such as adding validations and styling. Note that pSaveEditableRow only switches the row to back view mode when there are no validation errors.
Moreover you may use setting pEditableRowDisabled property as true to disable editing for that particular row and in case you need to display rows in edit mode by default use editingRowKeys property which is a map whose key is the dataKey of the record where value is any arbitrary number greater than zero.
<p-table [value]="cars" dataKey="vin" editMode="row">
<ng-template pTemplate="header">
<tr>
<th>Vin</th>
<th>Year</th>
<th>Brand</th>
<th>Color</th>
<th style="width:8em"></th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-editing="editing" let-ri="rowIndex">
<tr [pEditableRow]="rowData">
<td>
{{rowData.vin}}
</td>
<td>
<p-cellEditor>
<ng-template pTemplate="input">
<input pInputText type="text" [(ngModel)]="rowData.year" year>
</ng-template>
<ng-template pTemplate="output">
{{rowData.year}}
</ng-template>
</p-cellEditor>
</td>
<td>
<p-cellEditor>
<ng-template pTemplate="input">
<p-dropdown [options]="brands" [(ngModel)]="rowData.brand" [style]="{'width':'100%'}"></p-dropdown>
</ng-template>
<ng-template pTemplate="output">
{{rowData.brand}}
</ng-template>
</p-cellEditor>
</td>
<td>
<p-cellEditor>
<ng-template pTemplate="input">
<input pInputText type="text" [(ngModel)]="rowData.color">
</ng-template>
<ng-template pTemplate="output">
{{rowData.color}}
</ng-template>
</p-cellEditor>
</td>
<td style="text-align:center">
<button *ngIf="!editing" pButton type="button" pInitEditableRow icon="pi pi-pencil" class="ui-button-info" (click)="onRowEditInit(rowData)"></button>
<button *ngIf="editing" pButton type="button" pSaveEditableRow icon="pi pi-check" class="ui-button-success" style="margin-right: .5em" (click)="onRowEditSave(rowData)"></button>
<button *ngIf="editing" pButton type="button" pCancelEditableRow icon="pi pi-times" class="ui-button-danger" (click)="onRowEditCancel(rowData, ri)"></button>
</td>
</tr>
</ng-template>
</p-table>
export class TableEditDemo implements OnInit {
cars: Car[];
brands: SelectItem[];
clonedCars: { [s: string]: Car; } = {};
constructor(private carService: CarService) { }
ngOnInit() {
this.carService.getCarsSmall().then(cars => this.cars = cars);
this.brands = [
{label: 'Audi', value: 'Audi'},
{label: 'BMW', value: 'BMW'},
{label: 'Fiat', value: 'Fiat'},
{label: 'Ford', value: 'Ford'},
{label: 'Honda', value: 'Honda'},
{label: 'Jaguar', value: 'Jaguar'},
{label: 'Mercedes', value: 'Mercedes'},
{label: 'Renault', value: 'Renault'},
{label: 'VW', value: 'VW'},
{label: 'Volvo', value: 'Volvo'}
];
}
onRowEditInit(car: Car) {
this.clonedCars[car.vin] = {...car};
}
onRowEditSave(car: Car) {
if (car.year > 0)
delete this.clonedCars[car.vin];
else
this.messageService.add({severity:'error', summary: 'Error', detail:'Year is required'});
}
onRowEditCancel(car: Car, index: number) {
this.cars[index] = this.clonedCars[car.vin];
delete this.clonedCars[car.vin];
}
}
See the live example.
Expandable Rows
Row expansion allows displaying detailed content for a particular row. To use this feature, add a template named rowexpansion and use the pRowToggler directive whose value is the row data instance on an element of your choice whose click event toggles the expansion. This enables providing your custom UI such as buttons, links and so on. Example below uses an anchor with an icon as a toggler. Setting pRowTogglerDisabled as true disables the toggle event for the element.
<p-table [columns]="cols" [value]="cars" dataKey="vin">
<ng-template pTemplate="header" let-columns>
<tr>
<th style="width: 2.25em"></th>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-expanded="expanded" let-columns="columns">
<tr>
<td>
<a href="#" [pRowToggler]="rowData">
<i [ngClass]="expanded ? 'fa fa-fw fa-chevron-circle-down' : 'fa fa-fw fa-chevron-circle-right'"></i>
</a>
</td>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
<ng-template pTemplate="rowexpansion" let-rowData let-columns="columns">
<tr>
<td [attr.colspan]="columns.length + 1">
<div class="ui-g ui-fluid" style="font-size:16px;padding:20px">
<div class="ui-g-12 ui-md-3" style="text-align:center">
<img [attr.alt]="rowData.brand" src="assets/showcase/images/demo/car/{{rowData.brand}}.png">
</div>
<div class="ui-g-12 ui-md-9">
<div class="ui-g">
<div class="ui-g-12">
<b>Vin:</b> {{rowData.vin}}
</div>
<div class="ui-g-12">
<b>Vin:</b> {{rowData.color}}
</div>
<div class="ui-g-12">
<b>Brand:</b> {{rowData.brand}}
</div>
<div class="ui-g-12">
<b>Color:</b> {{rowData.color}}
</div>
</div>
</div>
</div>
</td>
</tr>
</ng-template>
</p-table>
Multiple rows can be expanded at the same time, if you prefer a single row expansion at any time set rowExpandMode property to "single". All rows are collapsed initially and providing expandedRowKeys property whose value is the dataKeys of the rows to be expanded enables rendering these rows as expanded. A dataKey must be defined for this feature.
<p-table [columns]="cols" [value]="cars" dataKey="vin" [expandedRowKeys]="expandedRows">
...
</p-table>
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. For dynamic columns, setting pResizableColumnDisabled property as true disables resizing for that particular column.
<p-table [columns]="cols" [value]="cars" [resizableColumns]="true">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns" pResizableColumn>
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns" class="ui-resizable-column">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
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.
<p-table [value]="cars" [resizableColumns]="true">
<ng-template pTemplate="header">
<tr>
<th style="width:20%">Vin</th>
<th style="width:30%">Year</th>
<th style="width:15%">Brand</th>
<th style="width:35%">Color</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-car>
<tr>
<td>{{car.vin}}</td>
<td>{{car.year}}</td>
<td>{{car.brand}}</td>
<td>{{car.color}}</td>
</tr>
</ng-template>
</p-table>
Note: Scrollable tables require a column group to support resizing.
<p-table [columns]="cols" [value]="cars" [scrollable]="true" scrollHeight="200px" [resizableColumns]="true">
<ng-template pTemplate="colgroup" let-columns>
<colgroup>
<col *ngFor="let col of columns">
</colgroup>
</ng-template>
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns" pResizableColumn>
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns" class="ui-resizable-column">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
See the live example.
Column Reordering
Columns can be reordered using drag drop by setting the reorderableColumns to true and adding pReorderableColumn directive to the columns that can be dragged. Note that columns should be dynamic for reordering to work. For dynamic columns, setting pReorderableColumnDisabled property as true disables reordering for that particular column.
<p-table [columns]="cols" [value]="cars" [reorderableColumns]="true">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns" pReorderableColumn>
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
See the live example.
Rows Reordering
Row reordering is enabled by adding pReorderableRow directive with a row index binding to the rows that can be reordered with drag and drop. The optional pReorderableRowDisabled property is available to disable dragging for a particular row. In addition, drag handle should get pReorderableRowHandle directive to specify which element is used to initiate the dragging.
<p-table [columns]="cols" [value]="cars">
<ng-template pTemplate="header" let-columns>
<tr>
<th style="width:2em"></th>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns" let-index="rowIndex">
<tr [pReorderableRow]="index">
<td>
<i class="fa fa-bars" pReorderableRowHandle></i>
</td>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
See the live example.
Data Export
Table can export its data in CSV format using exportCSV() method. By default whole data is exported, if you'd like to export only the selection then pass a config object with selectionOnly property as true. Note that columns should be dynamic for export functionality to work and column objects must define field/header properties.
<p-table #tt [columns]="cols" [value]="cars" selectionMode="multiple" [(selection)]="selectedCars">
<ng-template pTemplate="caption">
<div class="ui-helper-clearfix">
<button type="button" pButton icon="fa-file-o" iconPos="left" label="All Data" (click)="tt.exportCSV()" style="float:left"></button>
<button type="button" pButton icon="fa-file" iconPos="left" label="Selection Only" (click)="tt.exportCSV({selectionOnly:true})" style="float:right"></button>
</div>
</ng-template>
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr [pSelectableRow]="rowData">
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
See the live example.
Scrolling
DataTable supports both horizontal and vertical scrolling as well as frozen columns and rows. Additionally, virtualScroll mode enables dealing with large datasets by loading data on demand during scrolling.
Sample below uses vertical scrolling where headers are fixed and data is scrollable.
<p-table [columns]="cols" [value]="cars" [scrollable]="true" scrollHeight="200px">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
In horizontal scrolling on the other hand, it is important to give fixed widths to columns. In general when customizing the column widths of scrollable tables, use colgroup as below to avoid misalignment issues as it will apply both the header, body and footer sections which are different separate elements internally.
<p-table [columns]="cols" [value]="cars" [scrollable]="true" [style]="{width:'500px'}">
<ng-template pTemplate="colgroup" let-columns>
<colgroup>
<col *ngFor="let col of columns" style="width:250px">
</colgroup>
</ng-template>
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
Horizontal and Vertical scrolling can be combined as well on the same table.
<p-table [columns]="cols" [value]="cars3" [scrollable]="true" [style]="{width:'500px'}" scrollHeight="200px">
<ng-template pTemplate="colgroup" let-columns>
<colgroup>
<col *ngFor="let col of columns" style="width:250px">
</colgroup>
</ng-template>
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
Certain rows can be fixed by using the frozenValue property along with the "frozenrows" template.
<p-table [columns]="cols" [value]="cars4" [frozenValue]="frozenCars" [scrollable]="true" scrollHeight="200px">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="frozenrows" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
<b>{{rowData[col.field]}}</b>
</td>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
Particular columns can be made fixed where others remain scrollable, there are two ways to implement this functionality, either define a frozenColumns property if your frozen columns are dynamic or use frozenbody template. The width of the frozen section also must be defined with frozenWidth property. Templates including header, body and footer apply to the frozen section as well, however if require different content for the frozen section use frozenheader, frozenbody and frozenfooter instead. First example below uses dynamic frozen columns and second one demonstrates how to use frozen templates with column grouping.
<p-table [columns]="scrollableCols" [frozenColumns]="frozenCols" [value]="cars5" [scrollable]="true" scrollHeight="200px" frozenWidth="200px">
<ng-template pTemplate="colgroup" let-columns>
<colgroup>
<col *ngFor="let col of columns" style="width:200px">
</colgroup>
</ng-template>
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
<p-table [value]="sales" [scrollable]="true" scrollHeight="150px" frozenWidth="200px">
<ng-template pTemplate="frozenheader">
<tr>
<th style="width:200px;height:84px">Brand</th>
</tr>
</ng-template>
<ng-template pTemplate="frozenbody" let-sale>
<tr>
<td>{{sale.brand}}</td>
</tr>
</ng-template>
<ng-template pTemplate="header">
<tr>
<th colspan="4">Sale Rate</th>
</tr>
<tr>
<th colspan="2">Sales</th>
<th colspan="2">Profits</th>
</tr>
<tr>
<th>Last Year</th>
<th>This Year</th>
<th>Last Year</th>
<th>This Year</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-sale>
<tr>
<td>{{sale.lastYearSale}}</td>
<td>{{sale.thisYearSale}}</td>
<td>{{sale.lastYearProfit}}</td>
<td>{{sale.thisYearProfit}}</td>
</tr>
</ng-template>
</p-table>
When frozen columns are enabled, frozen and scrollable cells may have content with varying height which leads to misalignment. To avoid a performance hit, Table avoids expensive calculations to align the row heights as it can be easily done with CSS manually.
.ui-table .ui-table-frozen-view .ui-table-tbody > tr > td,
.ui-table .ui-table-unfrozen-view .ui-table-tbody > tr > td {
height: 24px !important;
}
When column widths need to vary or resizable columns is activated, use colgroup template to avoid misalignment issues and apply percentage values since table width is 100%.
<p-table [columns]="cols" [value]="cars" [scrollable]="true" scrollHeight="200px">
<ng-template pTemplate="colgroup" let-columns>
<colgroup>
<col *ngFor="let col of columns" [style.width]="col.width">
</colgroup>
</ng-template>
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
Virtual Scrolling is used with lazy loading to fetch data on demand during scrolling. For smooth scrolling twice the amount of rows property is loaded on a lazy load event. In addition, to avoid performance problems row height is not calculated automatically and should be provided using virtualRowHeight property which defaults to 28px, in your row template also assign the height of the row with the same value for smooth scrolling. Note that variable row height is not supported due to the nature of the virtual scrolling behavior.
<p-table [columns]="cols" [value]="virtualCars" [scrollable]="true" [rows]="20" scrollHeight="200px" [virtualRowHeight]="30"
[virtualScroll]="true" (onLazyLoad)="loadDataOnScroll($event)" [lazy]="true" [totalRecords]="totalRecords">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr style="height:30px">
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
Instead of using the built-in loading mask indicator, an special "loadingbody" template is available to provide feedback to the users about the loading status of a scroll event.
<p-table [columns]="cols" [value]="virtualCars" [scrollable]="true" [rows]="20" scrollHeight="200px" [virtualScroll]="true" (onLazyLoad)="loadDataOnScroll($event)"
[lazy]="true" [totalRecords]="totalRecords" [virtualRowHeight]="34" [showLoader]="false">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr style="height:34px">
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
<ng-template pTemplate="loadingbody" let-columns="columns">
<tr style="height:34px">
<td *ngFor="let col of columns">
<div class="loading-text"></div>
</td>
</tr>
</ng-template>
</p-table>
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 how the data should be loaded. 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-table [columns]="cols" [value]="cars" [lazy]="true" (onLazyLoad)="loadCarsLazy($event)" [paginator]="true" [rows]="10" [totalRecords]="totalRecords">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
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
//globalFilter: Value of the global filter if available
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.
TableState
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 and row selection.
<p-table #dt1 [columns]="cols" [value]="cars" [paginator]="true" [rows]="10" dataKey="vin" [resizableColumns]="true" [reorderableColumns]="true"
selectionMode="single" [(selection)]="selectedCar" stateStorage="session" stateKey="statedemo-session">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns" [pSortableColumn]="col.field" pResizableColumn pReorderableColumn>
{{col.header}}
<p-sortIcon [field]="col.field"></p-sortIcon>
</th>
</tr>
<tr>
<th *ngFor="let col of columns" [ngSwitch]="col.field" class="ui-fluid">
<input pInputText type="text" (input)="dt1.filter($event.target.value, col.field, col.filterMatchMode)" [value]="dt1.filters[col.field]?.value">
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr [pSelectableRow]="rowData">
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
See the live example.
Responsive
Table 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 and adding an element whose class name is "ui-column-title" to the body cells.
<p-table [columns]="cols" [value]="cars" [responsive]="true">
<ng-template pTemplate="caption">
List of Cars
</ng-template>
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
<span class="ui-column-title">{{col.header}}</span>
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
<ng-template pTemplate="summary">
There are {{cars?.length}} cars
</ng-template>
</p-table>
See the live example.
EmptyMessage
When there is no data, emptymessage template can be used to display a message.
<p-table [value]="cars">
<ng-template pTemplate="header">
<tr>
<th>Vin</th>
<th>Year</th>
<th>Brand</th>
<th>Color</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-car>
<tr>
<td>{{car.vin}}</td>
<td>{{car.year}}</td>
<td>{{car.brand}}</td>
<td>{{car.color}}</td>
</tr>
</ng-template>
<ng-template pTemplate="emptymessage" let-columns>
<tr>
<td [attr.colspan]="columns.length">
No records found
</td>
</tr>
</ng-template>
</p-table>
Loading Status
Table has a loading property, when enabled a spinner icon is displayed to indicate data load. An optional loadingIcon property can be passed in case you'd like a different loading icon.
<p-table [value]="cars" [loading]="loading">
<ng-template pTemplate="header">
<tr>
<th>Vin</th>
<th>Year</th>
<th>Brand</th>
<th>Color</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-car>
<tr>
<td>{{car.vin}}</td>
<td>{{car.year}}</td>
<td>{{car.brand}}</td>
<td>{{car.color}}</td>
</tr>
</ng-template>
</ng-template>
</p-table>
export class DataTableDemo implements OnInit {
loading: boolean;
cars: Car[];
constructor(private carService: CarService) { }
ngOnInit() {
this.loading = true;
setTimeout(() => {
this.carService.getCarsSmall().then(cars => this.cars = cars);
this.loading = false;
}, 1000);
}
}
Styling Certain Rows and Columns
Certain rows and cells can easily be styled using templating features. In example below, the row whose vin property is '123' will get the 'success' style class. Example here paint the background of the last cell using a colgroup and highlights rows whose year is older than 2000.
<p-table [columns]="cols" [value]="cars">
<ng-template pTemplate="colgroup" let-columns>
<colgroup>
<col>
<col>
<col>
<col style="background-color:#FFD54F !important">
</colgroup>
</ng-template>
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr [ngClass]="rowData.year > 2010 ? 'old-car' : null">
<td *ngFor="let col of columns" [ngClass]="rowData[col.field] < 2000 ? 'very-old-car' : null">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
See the live example.
Performance Tips
- When selection is enabled use dataKey to avoid deep checking when comparing objects.
- Use rowTrackBy to avoid unnecessary dom operations.
- Prefer lazy loading for large datasets.
Properties
Name | Type | Default | Description |
---|---|---|---|
value | array | null | An array of objects to display. |
columns | array | null | An array of objects to represent dynamic columns. |
frozenColumns | array | null | An array of objects to represent dynamic columns that are frozen. |
frozenValue | array | null | An array of objects to display as frozen. |
style | string | null | Inline style of the component. |
styleClass | string | null | Style class of the component. |
tableStyle | any | null | Inline style of the table. |
tableStyleClass | string | null | Style class of the table. |
paginator | boolean | false | When specified as true, enables the pagination. |
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. |
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 |
alwaysShowPaginator | boolean | true | Whether to show it even there is only one page. |
paginatorPosition | string | bottom | Position of the paginator, options are "top","bottom" or "both". |
currentPageReportTemplate | string | {currentPage} of {totalPages} | Text to display the current page information. |
showCurrentPageReport | boolean | false | Whether to display current page report. |
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 | 1 | Order to sort when default sorting is enabled. |
multiSortMeta | array | null | An array of SortMeta objects to sort the data by default in multiple sort mode. |
rowGroupMode | string | null | Type of the row grouping, valid values are "subheader" and "rowspan". |
defaultSortOrder | number | 1 | Sort order to use when an unsorted column gets sorted by user interaction. |
customSort | boolean | false | Whether to use the default sorting or a custom one using sortFunction. |
sortFunction | function | null | A function to implement custom sorting, refer to sorting section for details. |
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. |
contextMenuSelection | any | null | Selected row with a context menu. |
contextMenuSelectionMode | string | separate | Defines the behavior of context menu selection, in "separate" mode context menu updates contextMenuSelection propertty whereas in joint mode selection property is used instead so that when row selection is enabled, both row selection and context menu selection use the same property. |
dataKey | string | null | A property to uniquely identify a record in data. |
metaKeySelection | boolean | true | Defines whether metaKey is should be considered for the selection. On touch enabled devices, metaKeySelection is turned off automatically. |
rowTrackBy | Function | null | Function to optimize the dom operations by delegating to ngForTrackBy, default algoritm checks for object identity. |
lazy | boolean | false | Defines if data is loaded and interacted with in lazy manner. |
lazyLoadOnInit | boolean | true | Whether to call lazy loading on initialization. |
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. |
csvSeparator | string | , | Character to use as the csv separator. |
exportFilename | string | download | Name of the exported file. |
filters | array | null | An array of FilterMetadata objects to provide external filters. |
filterDelay | number | 300 | Delay in milliseconds before filtering the data. |
globalFilterFields | array | null | An array of fields as string to use in global filtering. |
expandedRowKeys | {[s: string]: boolean;} | null | Map instance to keep the expanded rows where key of the map is the data key of the row. |
rowExpandMode | string | multiple | Whether multiple rows can be expanded at any time. Valid values are "multiple" and "single". |
scrollable | boolean | false | When specifies, enables horizontal and/or vertical scrolling. |
scrollHeight | string | null | Height of the scroll viewport in fixed pixels, percentage or a calc expression. |
virtualScroll | boolean | false | Whether the data should be loaded on demand during scroll. |
virtualScrollDelay | number | 150 | Delay in virtual scroll before doing a call to lazy load. |
virtualRowHeight | number | 28 | Height of a row to use in calculations of virtual scrolling. |
frozenWidth | string | null | Width of the frozen columns container. |
responsive | boolean | false | Defines if the columns should be stacked in smaller screens. |
contextMenu | ContextMenu | null | Local ng-template varilable of a ContextMenu. |
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. |
loading | boolean | false | Displays a loader to indicate data load is in progress. |
loadingIcon | string | fa-circle-o-notch | The icon to show while indicating data load is in progress. |
showLoader | boolean | true | Whether to show the loading mask when loading property is true. |
rowHover | boolean | false | Adds hover effect to rows without the need for selectionMode. |
paginatorDropdownAppendTo | any | null | Target element to attach the paginator dropdown overlay, valid values are "body" or a local ng-template variable of another element. |
autoLayout | boolean | false | Whether the cell widths scale according to their content or not. |
resetPageOnSort | boolean | true | When true, resets paginator to first page after sorting. |
exportFunction | function | null | A function to implement custom export. Need to return string value. event.data: Field data. event.field: Column field. |
stateKey | string | null | Unique identifier of a stateful table to use in state storage. |
stateStorage | string | session | Defines where a stateful table keeps its state, valid values are "session" for sessionStorage and "local" for localStorage. |
editMode | string | cell | Defines the editing mode, valid values are "cell" and "row". |
editingRowKeys | {[s: string]: boolean;} | null | Map instance to keep the rows being edited where key of the map is the data key of the row. |
Events
Name | Parameters | Description |
---|---|---|
onRowSelect | event.originalEvent: Browser event event.data: Selected data event.type: Type of selection, valid values are "row", "radiobutton" and "checkbox" event.index: Index of the row | 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. |
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. event.filteredValue: Filtered data after running the filtering. | Callback to invoke when data is filtered. |
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 event.multiSortMeta: An array of SortMeta objects used in multiple columns sorting. Each SortMeta has field and order properties. event.filters: FilterMetadata object having field as key and filter value, filter matchMode as value event.globalFilter: Value of the global filter if available | Callback to invoke when paging, sorting or filtering happens in lazy mode. |
onRowExpand | event.originalEvent: Browser event data: Row data to expand. | Callback to invoke when a row is expanded. |
onRowCollapse | event.originalEvent: Browser event data: Row data to collapse. | Callback to invoke when a row is collapsed. |
onContextMenuSelect | event.originalEvent: Browser event event.data: Selected data | Callback to invoke when a row is selected with right click. |
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. |
onRowReorder | event.dragIndex: Index of the dragged row event.dropIndex: Index of the drop location | Callback to invoke when a row is reordered. |
onEditInit | event.column: Column object of the cell event.data: Row data | Callback to invoke when a cell switches to edit mode. |
onEditComplete | event.column: Column object of the cell event.data: Row data event.index: Row index | Callback to invoke when cell edit is completed. |
onEditCancel | event.column: Column object of the cell event.data: Row data event.index: Row index | Callback to invoke when cell edit is cancelled with escape key. |
onHeaderCheckboxToggle | event.originalEvent: Browser event event.checked: State of the header checkbox | Callback to invoke when state of header checkbox changes. |
onStateSave | state: Table state | Callback to invoke table state is saved. |
onStateRestore | state: Table state | Callback to invoke table state is restored. |
Methods
Name | Parameters | Description |
---|---|---|
reset | - | Resets sort, filter and paginator state. |
clearState | - | Clears table state. |
exportCSV | config?.selectionOnly: Exports only the selection. | Exports the data in csv format. |
closeCellEdit | - | Closes the editing cell. |
Styling
Following is the list of structural style classes, for theming classes visit theming page.
Name | Element |
---|---|
ui-table | Container element. |
ui-table-caption | Caption element. |
ui-table-summary | Section section. |
ui-sortable-column | Sortable column header. |
ui-table-scrollable-header | Container of header in a scrollable table. |
ui-table-scrollable-body | Container of body in a scrollable table. |
ui-table-scrollable-footer | Container of footer in a scrollable table. |
ui-table-responsive | Container element of a responsive datatable. |
ui-table-loading | Loader mask. |
ui-table-loading-content | Loader content. |
ui-table-wrapper | Loader content. |
ui-table-scrollable-wrapper | Loader content. |
ui-column-resizer-helper | Vertical resize indicator bar. To show the resize indicator bar set the "background-color" property. |
ui-table-reorder-indicator-top | Top indicator of column reordering. |
ui-table-reorder-indicator-top | Bottom indicator of column reordering. |
Dependencies
None.
Source
<h3 class="first">Basic</h3>
<p-table [value]="cars">
<ng-template pTemplate="header">
<tr>
<th>Vin</th>
<th>Year</th>
<th>Brand</th>
<th>Color</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-car>
<tr>
<td>{{car.vin}}</td>
<td>{{car.year}}</td>
<td>{{car.brand}}</td>
<td>{{car.color}}</td>
</tr>
</ng-template>
</p-table>
<h3>Dynamic Columns</h3>
<p-table [columns]="cols" [value]="cars">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
export class TableDemo 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' }
];
}
}