- ● 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.


Table - 图1





## Documentation


### Import




  1. 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.



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





  1. 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.



  1. 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.



  1. <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.



  1. 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.



  1. <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.



  1. <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.


NameParametersDescription
caption-Caption content of the table.
header$implicit: ColumnsContent 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: ColumnsContent of the tfoot element.
summary-Summary section to display below the table.
colgroup$implicit: ColumnsColGroup 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 collectionContent of the tbody element to display frozen rows.
frozenheader$implicit: ColumnsContent 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: ColumnsContent of the tfoot element in frozen side.
frozencolgroup$implicit: ColumnsColGroup element of the table to customize frozen columns.
emptymessage$implicit: ColumnsContent to display when there is no value to display.
paginatorleftstate: $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 recordsCustom content for the left section of the paginator.
paginatorrightstate: $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 recordsCustom content for the right section of the paginator.
loadingbodycolumns: 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.

  1. <p-table [columns]="cols" [value]="cars">
  2. <ng-template pTemplate="caption">
  3. List of Cars
  4. </ng-template>
  5. <ng-template pTemplate="header" let-columns>
  6. <tr>
  7. <th *ngFor="let col of columns">
  8. {{col.header}}
  9. </th>
  10. </tr>
  11. </ng-template>
  12. <ng-template pTemplate="body" let-rowData let-columns="columns">
  13. <tr>
  14. <td *ngFor="let col of columns">
  15. {{rowData[col.field]}}
  16. </td>
  17. </tr>
  18. </ng-template>
  19. <ng-template pTemplate="footer" let-columns>
  20. <tr>
  21. <td *ngFor="let col of columns">
  22. {{col.header}}
  23. </td>
  24. </tr>
  25. </ng-template>
  26. <ng-template pTemplate="summary">
  27. There are {{cars?.length}} cars
  28. </ng-template>
  29. </p-table>
  30.  

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.

  1. export class TableColGroupDemo implements OnInit {
  2. sales: any[];
  3. ngOnInit() {
  4. this.sales = [
  5. { brand: 'Apple', lastYearSale: '51%', thisYearSale: '40%', lastYearProfit: '$54,406.00', thisYearProfit: '$43,342' },
  6. { brand: 'Samsung', lastYearSale: '83%', thisYearSale: '96%', lastYearProfit: '$423,132', thisYearProfit: '$312,122' },
  7. { brand: 'Microsoft', lastYearSale: '38%', thisYearSale: '5%', lastYearProfit: '$12,321', thisYearProfit: '$8,500' },
  8. { brand: 'Philips', lastYearSale: '49%', thisYearSale: '22%', lastYearProfit: '$745,232', thisYearProfit: '$650,323,' },
  9. { brand: 'Song', lastYearSale: '17%', thisYearSale: '79%', lastYearProfit: '$643,242', thisYearProfit: '500,332' },
  10. { brand: 'LG', lastYearSale: '52%', thisYearSale: ' 65%', lastYearProfit: '$421,132', thisYearProfit: '$150,005' },
  11. { brand: 'Sharp', lastYearSale: '82%', thisYearSale: '12%', lastYearProfit: '$131,211', thisYearProfit: '$100,214' },
  12. { brand: 'Panasonic', lastYearSale: '44%', thisYearSale: '45%', lastYearProfit: '$66,442', thisYearProfit: '$53,322' },
  13. { brand: 'HTC', lastYearSale: '90%', thisYearSale: '56%', lastYearProfit: '$765,442', thisYearProfit: '$296,232' },
  14. { brand: 'Toshiba', lastYearSale: '75%', thisYearSale: '54%', lastYearProfit: '$21,212', thisYearProfit: '$12,533' }
  15. ];
  16. }
  17. }
  18.  
  1. <p-table [value]="sales">
  2. <ng-template pTemplate="header">
  3. <tr>
  4. <th rowspan="3">Brand</th>
  5. <th colspan="4">Sale Rate</th>
  6. </tr>
  7. <tr>
  8. <th colspan="2">Sales</th>
  9. <th colspan="2">Profits</th>
  10. </tr>
  11. <tr>
  12. <th>Last Year</th>
  13. <th>This Year</th>
  14. <th>Last Year</th>
  15. <th>This Year</th>
  16. </tr>
  17. </ng-template>
  18. <ng-template pTemplate="body" let-sale>
  19. <tr>
  20. <td>{{sale.brand}}</td>
  21. <td>{{sale.lastYearSale}}</td>
  22. <td>{{sale.thisYearSale}}</td>
  23. <td>{{sale.lastYearProfit}}</td>
  24. <td>{{sale.thisYearProfit}}</td>
  25. </tr>
  26. </ng-template>
  27. <ng-template pTemplate="footer">
  28. <tr>
  29. <td colspan="3">Totals</td>
  30. <td>$506,202</td>
  31. <td>$531,020</td>
  32. </tr>
  33. </ng-template>
  34. </p-table>
  35.  

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.

  1. export class TableRowGroupDemo implements OnInit {
  2. cars: Car[];
  3. rowGroupMetadata: any;
  4. constructor(private carService: CarService) { }
  5. ngOnInit() {
  6. this.carService.getCarsMedium().then(cars => {
  7. this.cars = cars;
  8. this.updateRowGroupMetaData();
  9. });
  10. }
  11. onSort() {
  12. this.updateRowGroupMetaData();
  13. }
  14. updateRowGroupMetaData() {
  15. this.rowGroupMetadata = {};
  16. if (this.cars) {
  17. for (let i = 0; i < this.cars.length; i++) {
  18. let rowData = this.cars[i];
  19. let brand = rowData.brand;
  20. if (i == 0) {
  21. this.rowGroupMetadata[brand] = { index: 0, size: 1 };
  22. }
  23. else {
  24. let previousRowData = this.cars[i - 1];
  25. let previousRowGroup = previousRowData.brand;
  26. if (brand === previousRowGroup)
  27. this.rowGroupMetadata[brand].size++;
  28. else
  29. this.rowGroupMetadata[brand] = { index: i, size: 1 };
  30. }
  31. }
  32. }
  33. }
  34. }
  35.  

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.

  1. <p-table [value]="cars" sortField="brand" sortMode="single" (onSort)="onSort()">
  2. <ng-template pTemplate="header">
  3. <tr>
  4. <th>Vin</th>
  5. <th>Year</th>
  6. <th>Color</th>
  7. </tr>
  8. </ng-template>
  9. <ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex">
  10. <tr class="ui-widget-header" *ngIf="rowGroupMetadata[rowData.brand].index === rowIndex">
  11. <td colspan="3">
  12. <span style="font-weight:bold">{{rowData.brand}}</span>
  13. </td>
  14. </tr>
  15. <tr>
  16. <td>{{rowData.vin}}</td>
  17. <td>{{rowData.year}}</td>
  18. <td>{{rowData.color}}</td>
  19. </tr>
  20. </ng-template>
  21. </p-table>
  22.  

An alternative grouping could be using rowspans for the group field.

  1. <p-table [value]="cars" sortField="brand" sortMode="single" (onSort)="onSort()">
  2. <ng-template pTemplate="header">
  3. <tr>
  4. <th>Brand</th>
  5. <th>Vin</th>
  6. <th>Year</th>
  7. <th>Color</th>
  8. </tr>
  9. </ng-template>
  10. <ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex">
  11. <tr>
  12. <td *ngIf="rowGroupMetadata[rowData.brand].index === rowIndex" [attr.rowspan]="rowGroupMetadata[rowData.brand].size">
  13. {{rowData.brand}}
  14. </td>
  15. <td>{{rowData.vin}}</td>
  16. <td>{{rowData.year}}</td>
  17. <td>{{rowData.color}}</td>
  18. </tr>
  19. </ng-template>
  20. </p-table>
  21.  

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.

  1. <p-table [columns]="cols" [value]="cars" [paginator]="true" [rows]="10">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th *ngFor="let col of columns">
  5. {{col.header}}
  6. </th>
  7. </tr>
  8. </ng-template>
  9. <ng-template pTemplate="body" let-rowData let-columns="columns">
  10. <tr>
  11. <td *ngFor="let col of columns">
  12. {{rowData[col.field]}}
  13. </td>
  14. </tr>
  15. </ng-template>
  16. </p-table>
  17.  

Paginator can also be controlled via model using a binding to the first property where changes trigger a pagination.

  1. <p-table [columns]="cols" [value]="cars" [paginator]="true" [rows]="10" [first]="first">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th *ngFor="let col of columns">
  5. {{col.header}}
  6. </th>
  7. </tr>
  8. </ng-template>
  9. <ng-template pTemplate="body" let-rowData let-columns="columns">
  10. <tr>
  11. <td *ngFor="let col of columns">
  12. {{rowData[col.field]}}
  13. </td>
  14. </tr>
  15. </ng-template>
  16. </p-table>
  17.  
  1. export class DataTablePageDemo implements OnInit {
  2. cars: Car[];
  3. first: number = 0;
  4. constructor(private carService: CarService) { }
  5. ngOnInit() {
  6. this.carService.getCarsSmall().then(cars => this.cars = cars);
  7. }
  8. reset() {
  9. this.first = 0;
  10. }
  11. }
  12.  

Paginator accepts custom content for the left and the right side via named templates.

  1. <p-table [columns]="cols" [value]="cars" [paginator]="true" [rows]="10" [first]="first">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th *ngFor="let col of columns">
  5. {{col.header}}
  6. </th>
  7. </tr>
  8. </ng-template>
  9. <ng-template pTemplate="body" let-rowData let-columns="columns">
  10. <tr>
  11. <td *ngFor="let col of columns">
  12. {{rowData[col.field]}}
  13. </td>
  14. </tr>
  15. </ng-template>
  16. <ng-template pTemplate="paginatorleft" let-state>
  17. {{state.first}}
  18. <button type="button" pButton icon="fa-refresh"></button>
  19. </ng-template>
  20. <ng-template pTemplate="paginatorright">
  21. <button type="button" pButton icon="fa-cloud-upload"></button>
  22. </ng-template>
  23. </p-table>
  24.  

Paginator templates gets the paginator state as an implicit variable that provides the following properties

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.

  1. <p-table [columns]="cols" [value]="cars1">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th *ngFor="let col of columns" [pSortableColumn]="col.field">
  5. {{col.header}}
  6. <p-sortIcon [field]="col.field"></p-sortIcon>
  7. </th>
  8. </tr>
  9. </ng-template>
  10. <ng-template pTemplate="body" let-rowData let-columns="columns">
  11. <tr>
  12. <td *ngFor="let col of columns">
  13. {{rowData[col.field]}}
  14. </td>
  15. </tr>
  16. </ng-template>
  17. </p-table>
  18.  

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.

  1. <p-table [value]="cars" sortMode="multiple">
  2.  

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

  1. <p-table [columns]="cols" [value]="cars1" sortField="year">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th *ngFor="let col of columns" [pSortableColumn]="col.field">
  5. {{col.header}}
  6. </th>
  7. </tr>
  8. </ng-template>
  9. <ng-template pTemplate="body" let-rowData let-columns="columns">
  10. <tr>
  11. <td *ngFor="let col of columns">
  12. {{rowData[col.field]}}
  13. </td>
  14. </tr>
  15. </ng-template>
  16. </p-table>
  17.  

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

  1. <p-table [columns]="cols" [value]="cars1" sortMode="multiple" [multiSortMeta]="multiSortMeta">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th *ngFor="let col of columns" [pSortableColumn]="col.field">
  5. {{col.header}}
  6. </th>
  7. </tr>
  8. </ng-template>
  9. <ng-template pTemplate="body" let-rowData let-columns="columns">
  10. <tr>
  11. <td *ngFor="let col of columns">
  12. {{rowData[col.field]}}
  13. </td>
  14. </tr>
  15. </ng-template>
  16. </p-table>
  17.  
  1. this.multiSortMeta = [];
  2. this.multiSortMeta.push({field: 'year', order: 1});
  3. this.multiSortMeta.push({field: 'brand', order: -1});
  4.  

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.

  1. export class CustomTableSortDemo implements OnInit {
  2. cars: Car[];
  3. constructor(private carService: CarService) { }
  4. ngOnInit() {
  5. this.carService.getCarsSmall().then(cars => this.cars = cars);
  6. this.cols = [
  7. { field: 'vin', header: 'Vin' },
  8. { field: 'year', header: 'Year' },
  9. { field: 'brand', header: 'Brand' },
  10. { field: 'color', header: 'Color' }
  11. ];
  12. }
  13. customSort(event: SortEvent) {
  14. //event.data = Data to sort
  15. //event.mode = 'single' or 'multiple' sort mode
  16. //event.field = Sort field in single sort
  17. //event.order = Sort order in single sort
  18. //event.multiSortMeta = SortMeta array in multiple sort
  19. event.data.sort((data1, data2) => {
  20. let value1 = data1[event.field];
  21. let value2 = data2[event.field];
  22. let result = null;
  23. if (value1 == null && value2 != null)
  24. result = -1;
  25. else if (value1 != null && value2 == null)
  26. result = 1;
  27. else if (value1 == null && value2 == null)
  28. result = 0;
  29. else if (typeof value1 === 'string' && typeof value2 === 'string')
  30. result = value1.localeCompare(value2);
  31. else
  32. result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0;
  33. return (event.order * result);
  34. });
  35. }
  36. }
  37.  
  1. <p-table [columns]="cols" [value]="cars" (sortFunction)="customSort($event)" [customSort]="true">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th *ngFor="let col of columns" [pSortableColumn]="col.field">
  5. {{col.header}}
  6. <p-sortIcon [field]="col.field"></p-sortIcon>
  7. </th>
  8. </tr>
  9. </ng-template>
  10. <ng-template pTemplate="body" let-rowData let-columns="columns">
  11. <tr>
  12. <td *ngFor="let col of columns">
  13. {{rowData[col.field]}}
  14. </td>
  15. </tr>
  16. </ng-template>
  17. </p-table>
  18.  

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.

  1. <p-table #tt [columns]="cols" [value]="cars" [paginator]="true" [rows]="10">
  2. <ng-template pTemplate="caption">
  3. <i class="fa fa-search" style="margin:4px 4px 0 0"></i>
  4. <input type="text" pInputText size="50" placeholder="Global Filter" (input)="tt.filterGlobal($event.target.value, 'contains')" style="width:auto">
  5. </ng-template>
  6. <ng-template pTemplate="header" let-columns>
  7. <tr>
  8. <th *ngFor="let col of columns">
  9. {{col.header}}
  10. </th>
  11. </tr>
  12. <tr>
  13. <th *ngFor="let col of columns" [ngSwitch]="col.field">
  14. <input *ngSwitchCase="'vin'" pInputText type="text" (input)="tt.filter($event.target.value, col.field, col.filterMatchMode)">
  15. <div *ngSwitchCase="'year'">
  16. {{yearFilter}}
  17. <i class="fa fa-close" (click)="yearFilter=null;tt.filter(null, col.field, col.filterMatchMode)"></i>
  18. <p-slider [style]="{'width':'100%','margin-top':'8px'}" [(ngModel)]="yearFilter" [min]="1970" [max]="2010" (onChange)="onYearChange($event, dt)"></p-slider>
  19. </div>
  20. <p-dropdown *ngSwitchCase="'brand'" [options]="brands" [style]="{'width':'100%'}" (onChange)="tt.filter($event.value, col.field, 'equals')"></p-dropdown>
  21. <p-multiSelect *ngSwitchCase="'color'" [options]="colors" defaultLabel="All Colors" (onChange)="tt.filter($event.value, col.field, 'in')"></p-multiSelect>
  22. </th>
  23. </tr>
  24. </ng-template>
  25. <ng-template pTemplate="body" let-rowData let-columns="columns">
  26. <tr [pSelectableRow]="rowData">
  27. <td *ngFor="let col of columns">
  28. {{rowData[col.field]}}
  29. </td>
  30. </tr>
  31. </ng-template>
  32. </p-table>
  33.  
  1. export class TableFilterDemo implements OnInit {
  2. cars: Car[];
  3. cols: any[];
  4. brands: SelectItem[];
  5. colors: SelectItem[];
  6. yearFilter: number;
  7. yearTimeout: any;
  8. constructor(private carService: CarService) { }
  9. ngOnInit() {
  10. this.carService.getCarsMedium().then(cars => this.cars = cars);
  11. this.brands = [
  12. { label: 'All Brands', value: null },
  13. { label: 'Audi', value: 'Audi' },
  14. { label: 'BMW', value: 'BMW' },
  15. { label: 'Fiat', value: 'Fiat' },
  16. { label: 'Honda', value: 'Honda' },
  17. { label: 'Jaguar', value: 'Jaguar' },
  18. { label: 'Mercedes', value: 'Mercedes' },
  19. { label: 'Renault', value: 'Renault' },
  20. { label: 'VW', value: 'VW' },
  21. { label: 'Volvo', value: 'Volvo' }
  22. ];
  23. this.colors = [
  24. { label: 'White', value: 'White' },
  25. { label: 'Green', value: 'Green' },
  26. { label: 'Silver', value: 'Silver' },
  27. { label: 'Black', value: 'Black' },
  28. { label: 'Red', value: 'Red' },
  29. { label: 'Maroon', value: 'Maroon' },
  30. { label: 'Brown', value: 'Brown' },
  31. { label: 'Orange', value: 'Orange' },
  32. { label: 'Blue', value: 'Blue' }
  33. ];
  34. this.cols = [
  35. { field: 'vin', header: 'Vin' },
  36. { field: 'year', header: 'Year' },
  37. { field: 'brand', header: 'Brand' },
  38. { field: 'color', header: 'Color' }
  39. ];
  40. }
  41. onYearChange(event, dt) {
  42. if (this.yearTimeout) {
  43. clearTimeout(this.yearTimeout);
  44. }
  45. this.yearTimeout = setTimeout(() => {
  46. tt.filter(event.value, 'year', 'gt');
  47. }, 250);
  48. }
  49. }
  50.  

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.

  1. <p-table [value]="cars" [paginator]="true" [rows]="10" [globalFilterFields]="['vin','year']">
  2. //content
  3. </p-table>
  4.  

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.

  1. export class DataTableDemo implements OnInit {
  2. cars: Car[];
  3. selectedCar: Car;
  4. constructor(private carService: CarService) { }
  5. ngOnInit() {
  6. this.carService.getCarsSmall().then(cars => this.cars = cars);
  7. }
  8. }
  9.  
  1. <p-table [columns]="cols" [value]="cars" selectionMode="single" [(selection)]="selectedCar">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th *ngFor="let col of columns">
  5. {{col.header}}
  6. </th>
  7. </tr>
  8. </ng-template>
  9. <ng-template pTemplate="body" let-rowData let-columns="columns">
  10. <tr [pSelectableRow]="rowData">
  11. <td *ngFor="let col of columns">
  12. {{rowData[col.field]}}
  13. </td>
  14. </tr>
  15. </ng-template>
  16. </p-table>
  17.  

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.

  1. export class DataTableDemo implements OnInit {
  2. cars: Car[];
  3. selectedCars: Car[];
  4. constructor(private carService: CarService) { }
  5. ngOnInit() {
  6. this.carService.getCarsSmall().then(cars => this.cars = cars);
  7. }
  8. }
  9.  
  1. <p-table [columns]="cols" [value]="cars" selectionMode="multiple" [(selection)]="selectedCars">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th *ngFor="let col of columns">
  5. {{col.header}}
  6. </th>
  7. </tr>
  8. </ng-template>
  9. <ng-template pTemplate="body" let-rowData let-columns="columns" let-rowIndex="rowIndex">
  10. <tr [pSelectableRow]="rowData" [pSelectableRowIndex]="rowIndex">
  11. <td *ngFor="let col of columns">
  12. {{rowData[col.field]}}
  13. </td>
  14. </tr>
  15. </ng-template>
  16. </p-table>
  17.  

Single selection using a radiobutton can be done by using p-tableRadioButton component.

  1. <p-table [columns]="cols" [value]="cars" [(selection)]="selectedCar" dataKey="vin">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th style="width: 2.25em"></th>
  5. <th *ngFor="let col of columns">
  6. {{col.header}}
  7. </th>
  8. </tr>
  9. </ng-template>
  10. <ng-template pTemplate="body" let-rowData let-columns="columns">
  11. <tr>
  12. <td>
  13. <p-tableRadioButton [value]="rowData"></p-tableRadioButton>
  14. </td>
  15. <td *ngFor="let col of columns">
  16. {{rowData[col.field]}}
  17. </td>
  18. </tr>
  19. </ng-template>
  20. <ng-template pTemplate="summary">
  21. <div style="text-align: left">
  22. Selected Car: {{selectedCar4 ? selectedCar4.vin + ' - ' + selectedCar4.brand + ' - ' + selectedCar4.year + ' - ' + selectedCar4.color: 'none'}}
  23. </div>
  24. </ng-template>
  25. </p-table>
  26.  

Similarly p-tableCheckbox and p-tableHeaderCheckbox elements are provide to implement checkbox based multiple selection.

  1. <p-table [columns]="cols" [value]="cars" [(selection)]="selectedCars" dataKey="vin">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th style="width: 2.25em">
  5. <p-tableHeaderCheckbox></p-tableHeaderCheckbox>
  6. </th>
  7. <th *ngFor="let col of columns">
  8. {{col.header}}
  9. </th>
  10. </tr>
  11. </ng-template>
  12. <ng-template pTemplate="body" let-rowData let-columns="columns">
  13. <tr>
  14. <td>
  15. <p-tableCheckbox [value]="rowData"></p-tableCheckbox>
  16. </td>
  17. <td *ngFor="let col of columns">
  18. {{rowData[col.field]}}
  19. </td>
  20. </tr>
  21. </ng-template>
  22. </p-table>
  23.  

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.

  1. <ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex" let-columns="columns">
  2. <tr [pSelectableRow]="rowData">
  3. <td>
  4. <p-tableCheckbox [value]="rowData" [disabled]="rowData.year > 2010" [index]="rowIndex"></p-tableCheckbox>
  5. </td>
  6. <td *ngFor="let col of columns">
  7. {{rowData[col.field]}}
  8. </td>
  9. </tr>
  10. </ng-template>
  11.  

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.

  1. <p-table [columns]="cols" [value]="cars" [(contextMenuSelection)]="selectedCar" [contextMenu]="cm">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th *ngFor="let col of columns">
  5. {{col.header}}
  6. </th>
  7. </tr>
  8. </ng-template>
  9. <ng-template pTemplate="body" let-rowData let-columns="columns" let-rowIndex="rowIndex">
  10. <tr [pContextMenuRow]="rowData" [pContextMenuRowIndex]="rowIndex">
  11. <td *ngFor="let col of columns">
  12. {{rowData[col.field]}}
  13. </td>
  14. </tr>
  15. </ng-template>
  16. </p-table>
  17. <p-contextMenu #cm [model]="items"></p-contextMenu>
  18.  

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.

  1. <p-table [columns]="cols" [value]="cars" selectionMode="single" [(selection)]="selectedCar" [contextMenu]="cm" contextMenuSelectionMode="joint">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th *ngFor="let col of columns">
  5. {{col.header}}
  6. </th>
  7. </tr>
  8. </ng-template>
  9. <ng-template pTemplate="body" let-rowData let-columns="columns">
  10. <tr [pSelectableRow]="rowData" [pContextMenuRow]="rowData">
  11. <td *ngFor="let col of columns">
  12. {{rowData[col.field]}}
  13. </td>
  14. </tr>
  15. </ng-template>
  16. </p-table>
  17. <p-contextMenu #cm [model]="items"></p-contextMenu>
  18.  

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.

  1. <p-table [columns]="cols" [value]="cars">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th>Vin</th>
  5. <th>Year</th>
  6. <th>Brand</th>
  7. <th>Color</th>
  8. </tr>
  9. </ng-template>
  10. <ng-template pTemplate="body" let-rowData let-columns="columns">
  11. <tr>
  12. <td pEditableColumn>
  13. <p-cellEditor>
  14. <ng-template pTemplate="input">
  15. <input type="text" [(ngModel)]="rowData.vin">
  16. </ng-template>
  17. <ng-template pTemplate="output">
  18. {{rowData.vin}}
  19. </ng-template>
  20. </p-cellEditor>
  21. </td>
  22. <td pEditableColumn>
  23. <p-cellEditor>
  24. <ng-template pTemplate="input">
  25. <input type="text" [(ngModel)]="rowData.year" required>
  26. </ng-template>
  27. <ng-template pTemplate="output">
  28. {{rowData.year}}
  29. </ng-template>
  30. </p-cellEditor>
  31. </td>
  32. <td pEditableColumn>
  33. <p-cellEditor>
  34. <ng-template pTemplate="input">
  35. <input type="text" [(ngModel)]="rowData.brand">
  36. </ng-template>
  37. <ng-template pTemplate="output">
  38. {{rowData.brand}}
  39. </ng-template>
  40. </p-cellEditor>
  41. </td>
  42. <td pEditableColumn>
  43. <p-cellEditor>
  44. <ng-template pTemplate="input">
  45. <input type="text" [(ngModel)]="rowData.color">
  46. </ng-template>
  47. <ng-template pTemplate="output">
  48. {{rowData.color}}
  49. </ng-template>
  50. </p-cellEditor>
  51. </td>
  52. </tr>
  53. </ng-template>
  54. </p-table>
  55.  

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.

  1. <td [pEditableColumn]="rowData" [pEditableColumnField]="'year'">
  2.  

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.

  1. <td [pFocusCellSelector]="'input, .custom-edit-control'">
  2.  

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.

  1. <p-table [value]="cars" dataKey="vin" editMode="row">
  2. <ng-template pTemplate="header">
  3. <tr>
  4. <th>Vin</th>
  5. <th>Year</th>
  6. <th>Brand</th>
  7. <th>Color</th>
  8. <th style="width:8em"></th>
  9. </tr>
  10. </ng-template>
  11. <ng-template pTemplate="body" let-rowData let-editing="editing" let-ri="rowIndex">
  12. <tr [pEditableRow]="rowData">
  13. <td>
  14. {{rowData.vin}}
  15. </td>
  16. <td>
  17. <p-cellEditor>
  18. <ng-template pTemplate="input">
  19. <input pInputText type="text" [(ngModel)]="rowData.year" year>
  20. </ng-template>
  21. <ng-template pTemplate="output">
  22. {{rowData.year}}
  23. </ng-template>
  24. </p-cellEditor>
  25. </td>
  26. <td>
  27. <p-cellEditor>
  28. <ng-template pTemplate="input">
  29. <p-dropdown [options]="brands" [(ngModel)]="rowData.brand" [style]="{'width':'100%'}"></p-dropdown>
  30. </ng-template>
  31. <ng-template pTemplate="output">
  32. {{rowData.brand}}
  33. </ng-template>
  34. </p-cellEditor>
  35. </td>
  36. <td>
  37. <p-cellEditor>
  38. <ng-template pTemplate="input">
  39. <input pInputText type="text" [(ngModel)]="rowData.color">
  40. </ng-template>
  41. <ng-template pTemplate="output">
  42. {{rowData.color}}
  43. </ng-template>
  44. </p-cellEditor>
  45. </td>
  46. <td style="text-align:center">
  47. <button *ngIf="!editing" pButton type="button" pInitEditableRow icon="pi pi-pencil" class="ui-button-info" (click)="onRowEditInit(rowData)"></button>
  48. <button *ngIf="editing" pButton type="button" pSaveEditableRow icon="pi pi-check" class="ui-button-success" style="margin-right: .5em" (click)="onRowEditSave(rowData)"></button>
  49. <button *ngIf="editing" pButton type="button" pCancelEditableRow icon="pi pi-times" class="ui-button-danger" (click)="onRowEditCancel(rowData, ri)"></button>
  50. </td>
  51. </tr>
  52. </ng-template>
  53. </p-table>
  54.  
  1. export class TableEditDemo implements OnInit {
  2. cars: Car[];
  3. brands: SelectItem[];
  4. clonedCars: { [s: string]: Car; } = {};
  5. constructor(private carService: CarService) { }
  6. ngOnInit() {
  7. this.carService.getCarsSmall().then(cars => this.cars = cars);
  8. this.brands = [
  9. {label: 'Audi', value: 'Audi'},
  10. {label: 'BMW', value: 'BMW'},
  11. {label: 'Fiat', value: 'Fiat'},
  12. {label: 'Ford', value: 'Ford'},
  13. {label: 'Honda', value: 'Honda'},
  14. {label: 'Jaguar', value: 'Jaguar'},
  15. {label: 'Mercedes', value: 'Mercedes'},
  16. {label: 'Renault', value: 'Renault'},
  17. {label: 'VW', value: 'VW'},
  18. {label: 'Volvo', value: 'Volvo'}
  19. ];
  20. }
  21. onRowEditInit(car: Car) {
  22. this.clonedCars[car.vin] = {...car};
  23. }
  24. onRowEditSave(car: Car) {
  25. if (car.year > 0)
  26. delete this.clonedCars[car.vin];
  27. else
  28. this.messageService.add({severity:'error', summary: 'Error', detail:'Year is required'});
  29. }
  30. onRowEditCancel(car: Car, index: number) {
  31. this.cars[index] = this.clonedCars[car.vin];
  32. delete this.clonedCars[car.vin];
  33. }
  34. }
  35.  

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.

  1. <p-table [columns]="cols" [value]="cars" dataKey="vin">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th style="width: 2.25em"></th>
  5. <th *ngFor="let col of columns">
  6. {{col.header}}
  7. </th>
  8. </tr>
  9. </ng-template>
  10. <ng-template pTemplate="body" let-rowData let-expanded="expanded" let-columns="columns">
  11. <tr>
  12. <td>
  13. <a href="#" [pRowToggler]="rowData">
  14. <i [ngClass]="expanded ? 'fa fa-fw fa-chevron-circle-down' : 'fa fa-fw fa-chevron-circle-right'"></i>
  15. </a>
  16. </td>
  17. <td *ngFor="let col of columns">
  18. {{rowData[col.field]}}
  19. </td>
  20. </tr>
  21. </ng-template>
  22. <ng-template pTemplate="rowexpansion" let-rowData let-columns="columns">
  23. <tr>
  24. <td [attr.colspan]="columns.length + 1">
  25. <div class="ui-g ui-fluid" style="font-size:16px;padding:20px">
  26. <div class="ui-g-12 ui-md-3" style="text-align:center">
  27. <img [attr.alt]="rowData.brand" src="assets/showcase/images/demo/car/{{rowData.brand}}.png">
  28. </div>
  29. <div class="ui-g-12 ui-md-9">
  30. <div class="ui-g">
  31. <div class="ui-g-12">
  32. <b>Vin:</b> {{rowData.vin}}
  33. </div>
  34. <div class="ui-g-12">
  35. <b>Vin:</b> {{rowData.color}}
  36. </div>
  37. <div class="ui-g-12">
  38. <b>Brand:</b> {{rowData.brand}}
  39. </div>
  40. <div class="ui-g-12">
  41. <b>Color:</b> {{rowData.color}}
  42. </div>
  43. </div>
  44. </div>
  45. </div>
  46. </td>
  47. </tr>
  48. </ng-template>
  49. </p-table>
  50.  

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.

  1. <p-table [columns]="cols" [value]="cars" dataKey="vin" [expandedRowKeys]="expandedRows">
  2. ...
  3. </p-table>
  4.  

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.

  1. <p-table [columns]="cols" [value]="cars" [resizableColumns]="true">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th *ngFor="let col of columns" pResizableColumn>
  5. {{col.header}}
  6. </th>
  7. </tr>
  8. </ng-template>
  9. <ng-template pTemplate="body" let-rowData let-columns="columns">
  10. <tr>
  11. <td *ngFor="let col of columns" class="ui-resizable-column">
  12. {{rowData[col.field]}}
  13. </td>
  14. </tr>
  15. </ng-template>
  16. </p-table>
  17.  

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.

  1. <p-table [value]="cars" [resizableColumns]="true">
  2. <ng-template pTemplate="header">
  3. <tr>
  4. <th style="width:20%">Vin</th>
  5. <th style="width:30%">Year</th>
  6. <th style="width:15%">Brand</th>
  7. <th style="width:35%">Color</th>
  8. </tr>
  9. </ng-template>
  10. <ng-template pTemplate="body" let-car>
  11. <tr>
  12. <td>{{car.vin}}</td>
  13. <td>{{car.year}}</td>
  14. <td>{{car.brand}}</td>
  15. <td>{{car.color}}</td>
  16. </tr>
  17. </ng-template>
  18. </p-table>
  19.  

Note: Scrollable tables require a column group to support resizing.

  1. <p-table [columns]="cols" [value]="cars" [scrollable]="true" scrollHeight="200px" [resizableColumns]="true">
  2. <ng-template pTemplate="colgroup" let-columns>
  3. <colgroup>
  4. <col *ngFor="let col of columns">
  5. </colgroup>
  6. </ng-template>
  7. <ng-template pTemplate="header" let-columns>
  8. <tr>
  9. <th *ngFor="let col of columns" pResizableColumn>
  10. {{col.header}}
  11. </th>
  12. </tr>
  13. </ng-template>
  14. <ng-template pTemplate="body" let-rowData let-columns="columns">
  15. <tr>
  16. <td *ngFor="let col of columns" class="ui-resizable-column">
  17. {{rowData[col.field]}}
  18. </td>
  19. </tr>
  20. </ng-template>
  21. </p-table>
  22.  

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.

  1. <p-table [columns]="cols" [value]="cars" [reorderableColumns]="true">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th *ngFor="let col of columns" pReorderableColumn>
  5. {{col.header}}
  6. </th>
  7. </tr>
  8. </ng-template>
  9. <ng-template pTemplate="body" let-rowData let-columns="columns">
  10. <tr>
  11. <td *ngFor="let col of columns">
  12. {{rowData[col.field]}}
  13. </td>
  14. </tr>
  15. </ng-template>
  16. </p-table>
  17.  

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.

  1. <p-table [columns]="cols" [value]="cars">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th style="width:2em"></th>
  5. <th *ngFor="let col of columns">
  6. {{col.header}}
  7. </th>
  8. </tr>
  9. </ng-template>
  10. <ng-template pTemplate="body" let-rowData let-columns="columns" let-index="rowIndex">
  11. <tr [pReorderableRow]="index">
  12. <td>
  13. <i class="fa fa-bars" pReorderableRowHandle></i>
  14. </td>
  15. <td *ngFor="let col of columns">
  16. {{rowData[col.field]}}
  17. </td>
  18. </tr>
  19. </ng-template>
  20. </p-table>
  21.  

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.

  1. <p-table #tt [columns]="cols" [value]="cars" selectionMode="multiple" [(selection)]="selectedCars">
  2. <ng-template pTemplate="caption">
  3. <div class="ui-helper-clearfix">
  4. <button type="button" pButton icon="fa-file-o" iconPos="left" label="All Data" (click)="tt.exportCSV()" style="float:left"></button>
  5. <button type="button" pButton icon="fa-file" iconPos="left" label="Selection Only" (click)="tt.exportCSV({selectionOnly:true})" style="float:right"></button>
  6. </div>
  7. </ng-template>
  8. <ng-template pTemplate="header" let-columns>
  9. <tr>
  10. <th *ngFor="let col of columns">
  11. {{col.header}}
  12. </th>
  13. </tr>
  14. </ng-template>
  15. <ng-template pTemplate="body" let-rowData let-columns="columns">
  16. <tr [pSelectableRow]="rowData">
  17. <td *ngFor="let col of columns">
  18. {{rowData[col.field]}}
  19. </td>
  20. </tr>
  21. </ng-template>
  22. </p-table>
  23.  

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.

  1. <p-table [columns]="cols" [value]="cars" [scrollable]="true" scrollHeight="200px">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th *ngFor="let col of columns">
  5. {{col.header}}
  6. </th>
  7. </tr>
  8. </ng-template>
  9. <ng-template pTemplate="body" let-rowData let-columns="columns">
  10. <tr>
  11. <td *ngFor="let col of columns">
  12. {{rowData[col.field]}}
  13. </td>
  14. </tr>
  15. </ng-template>
  16. </p-table>
  17.  

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.

  1. <p-table [columns]="cols" [value]="cars" [scrollable]="true" [style]="{width:'500px'}">
  2. <ng-template pTemplate="colgroup" let-columns>
  3. <colgroup>
  4. <col *ngFor="let col of columns" style="width:250px">
  5. </colgroup>
  6. </ng-template>
  7. <ng-template pTemplate="header" let-columns>
  8. <tr>
  9. <th *ngFor="let col of columns">
  10. {{col.header}}
  11. </th>
  12. </tr>
  13. </ng-template>
  14. <ng-template pTemplate="body" let-rowData let-columns="columns">
  15. <tr>
  16. <td *ngFor="let col of columns">
  17. {{rowData[col.field]}}
  18. </td>
  19. </tr>
  20. </ng-template>
  21. </p-table>
  22.  

Horizontal and Vertical scrolling can be combined as well on the same table.

  1. <p-table [columns]="cols" [value]="cars3" [scrollable]="true" [style]="{width:'500px'}" scrollHeight="200px">
  2. <ng-template pTemplate="colgroup" let-columns>
  3. <colgroup>
  4. <col *ngFor="let col of columns" style="width:250px">
  5. </colgroup>
  6. </ng-template>
  7. <ng-template pTemplate="header" let-columns>
  8. <tr>
  9. <th *ngFor="let col of columns">
  10. {{col.header}}
  11. </th>
  12. </tr>
  13. </ng-template>
  14. <ng-template pTemplate="body" let-rowData let-columns="columns">
  15. <tr>
  16. <td *ngFor="let col of columns">
  17. {{rowData[col.field]}}
  18. </td>
  19. </tr>
  20. </ng-template>
  21. </p-table>
  22.  

Certain rows can be fixed by using the frozenValue property along with the "frozenrows" template.

  1. <p-table [columns]="cols" [value]="cars4" [frozenValue]="frozenCars" [scrollable]="true" scrollHeight="200px">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th *ngFor="let col of columns">
  5. {{col.header}}
  6. </th>
  7. </tr>
  8. </ng-template>
  9. <ng-template pTemplate="frozenrows" let-rowData let-columns="columns">
  10. <tr>
  11. <td *ngFor="let col of columns">
  12. <b>{{rowData[col.field]}}</b>
  13. </td>
  14. </tr>
  15. </ng-template>
  16. <ng-template pTemplate="body" let-rowData let-columns="columns">
  17. <tr>
  18. <td *ngFor="let col of columns">
  19. {{rowData[col.field]}}
  20. </td>
  21. </tr>
  22. </ng-template>
  23. </p-table>
  24.  

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.

  1. <p-table [columns]="scrollableCols" [frozenColumns]="frozenCols" [value]="cars5" [scrollable]="true" scrollHeight="200px" frozenWidth="200px">
  2. <ng-template pTemplate="colgroup" let-columns>
  3. <colgroup>
  4. <col *ngFor="let col of columns" style="width:200px">
  5. </colgroup>
  6. </ng-template>
  7. <ng-template pTemplate="header" let-columns>
  8. <tr>
  9. <th *ngFor="let col of columns">
  10. {{col.header}}
  11. </th>
  12. </tr>
  13. </ng-template>
  14. <ng-template pTemplate="body" let-rowData let-columns="columns">
  15. <tr>
  16. <td *ngFor="let col of columns">
  17. {{rowData[col.field]}}
  18. </td>
  19. </tr>
  20. </ng-template>
  21. </p-table>
  22. <p-table [value]="sales" [scrollable]="true" scrollHeight="150px" frozenWidth="200px">
  23. <ng-template pTemplate="frozenheader">
  24. <tr>
  25. <th style="width:200px;height:84px">Brand</th>
  26. </tr>
  27. </ng-template>
  28. <ng-template pTemplate="frozenbody" let-sale>
  29. <tr>
  30. <td>{{sale.brand}}</td>
  31. </tr>
  32. </ng-template>
  33. <ng-template pTemplate="header">
  34. <tr>
  35. <th colspan="4">Sale Rate</th>
  36. </tr>
  37. <tr>
  38. <th colspan="2">Sales</th>
  39. <th colspan="2">Profits</th>
  40. </tr>
  41. <tr>
  42. <th>Last Year</th>
  43. <th>This Year</th>
  44. <th>Last Year</th>
  45. <th>This Year</th>
  46. </tr>
  47. </ng-template>
  48. <ng-template pTemplate="body" let-sale>
  49. <tr>
  50. <td>{{sale.lastYearSale}}</td>
  51. <td>{{sale.thisYearSale}}</td>
  52. <td>{{sale.lastYearProfit}}</td>
  53. <td>{{sale.thisYearProfit}}</td>
  54. </tr>
  55. </ng-template>
  56. </p-table>
  57.  

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.

  1. .ui-table .ui-table-frozen-view .ui-table-tbody > tr > td,
  2. .ui-table .ui-table-unfrozen-view .ui-table-tbody > tr > td {
  3. height: 24px !important;
  4. }
  5.  

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%.

  1. <p-table [columns]="cols" [value]="cars" [scrollable]="true" scrollHeight="200px">
  2. <ng-template pTemplate="colgroup" let-columns>
  3. <colgroup>
  4. <col *ngFor="let col of columns" [style.width]="col.width">
  5. </colgroup>
  6. </ng-template>
  7. <ng-template pTemplate="header" let-columns>
  8. <tr>
  9. <th *ngFor="let col of columns">
  10. {{col.header}}
  11. </th>
  12. </tr>
  13. </ng-template>
  14. <ng-template pTemplate="body" let-rowData let-columns="columns">
  15. <tr>
  16. <td *ngFor="let col of columns">
  17. {{rowData[col.field]}}
  18. </td>
  19. </tr>
  20. </ng-template>
  21. </p-table>
  22.  

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.

  1. <p-table [columns]="cols" [value]="virtualCars" [scrollable]="true" [rows]="20" scrollHeight="200px" [virtualRowHeight]="30"
  2. [virtualScroll]="true" (onLazyLoad)="loadDataOnScroll($event)" [lazy]="true" [totalRecords]="totalRecords">
  3. <ng-template pTemplate="header" let-columns>
  4. <tr>
  5. <th *ngFor="let col of columns">
  6. {{col.header}}
  7. </th>
  8. </tr>
  9. </ng-template>
  10. <ng-template pTemplate="body" let-rowData let-columns="columns">
  11. <tr style="height:30px">
  12. <td *ngFor="let col of columns">
  13. {{rowData[col.field]}}
  14. </td>
  15. </tr>
  16. </ng-template>
  17. </p-table>
  18.  

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.

  1. <p-table [columns]="cols" [value]="virtualCars" [scrollable]="true" [rows]="20" scrollHeight="200px" [virtualScroll]="true" (onLazyLoad)="loadDataOnScroll($event)"
  2. [lazy]="true" [totalRecords]="totalRecords" [virtualRowHeight]="34" [showLoader]="false">
  3. <ng-template pTemplate="header" let-columns>
  4. <tr>
  5. <th *ngFor="let col of columns">
  6. {{col.header}}
  7. </th>
  8. </tr>
  9. </ng-template>
  10. <ng-template pTemplate="body" let-rowData let-columns="columns">
  11. <tr style="height:34px">
  12. <td *ngFor="let col of columns">
  13. {{rowData[col.field]}}
  14. </td>
  15. </tr>
  16. </ng-template>
  17. <ng-template pTemplate="loadingbody" let-columns="columns">
  18. <tr style="height:34px">
  19. <td *ngFor="let col of columns">
  20. <div class="loading-text"></div>
  21. </td>
  22. </tr>
  23. </ng-template>
  24. </p-table>
  25.  

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.

  1. <p-table [columns]="cols" [value]="cars" [lazy]="true" (onLazyLoad)="loadCarsLazy($event)" [paginator]="true" [rows]="10" [totalRecords]="totalRecords">
  2. <ng-template pTemplate="header" let-columns>
  3. <tr>
  4. <th *ngFor="let col of columns">
  5. {{col.header}}
  6. </th>
  7. </tr>
  8. </ng-template>
  9. <ng-template pTemplate="body" let-rowData let-columns="columns">
  10. <tr>
  11. <td *ngFor="let col of columns">
  12. {{rowData[col.field]}}
  13. </td>
  14. </tr>
  15. </ng-template>
  16. </p-table>
  17.  
  1. loadData(event: LazyLoadEvent) {
  2. //event.first = First row offset
  3. //event.rows = Number of rows per page
  4. //event.sortField = Field name to sort in single sort mode
  5. //event.sortOrder = Sort order as number, 1 for asc and -1 for dec in single sort mode
  6. //multiSortMeta: An array of SortMeta objects used in multiple columns sorting. Each SortMeta has field and order properties.
  7. //filters: Filters object having field as key and filter value, filter matchMode as value
  8. //globalFilter: Value of the global filter if available
  9. this.cars = //do a request to a remote datasource using a service and return the cars that match the lazy load criteria
  10. }
  11.  

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.

  1. <p-table #dt1 [columns]="cols" [value]="cars" [paginator]="true" [rows]="10" dataKey="vin" [resizableColumns]="true" [reorderableColumns]="true"
  2. selectionMode="single" [(selection)]="selectedCar" stateStorage="session" stateKey="statedemo-session">
  3. <ng-template pTemplate="header" let-columns>
  4. <tr>
  5. <th *ngFor="let col of columns" [pSortableColumn]="col.field" pResizableColumn pReorderableColumn>
  6. {{col.header}}
  7. <p-sortIcon [field]="col.field"></p-sortIcon>
  8. </th>
  9. </tr>
  10. <tr>
  11. <th *ngFor="let col of columns" [ngSwitch]="col.field" class="ui-fluid">
  12. <input pInputText type="text" (input)="dt1.filter($event.target.value, col.field, col.filterMatchMode)" [value]="dt1.filters[col.field]?.value">
  13. </th>
  14. </tr>
  15. </ng-template>
  16. <ng-template pTemplate="body" let-rowData let-columns="columns">
  17. <tr [pSelectableRow]="rowData">
  18. <td *ngFor="let col of columns">
  19. {{rowData[col.field]}}
  20. </td>
  21. </tr>
  22. </ng-template>
  23. </p-table>
  24.  

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.

  1. <p-table [columns]="cols" [value]="cars" [responsive]="true">
  2. <ng-template pTemplate="caption">
  3. List of Cars
  4. </ng-template>
  5. <ng-template pTemplate="header" let-columns>
  6. <tr>
  7. <th *ngFor="let col of columns">
  8. {{col.header}}
  9. </th>
  10. </tr>
  11. </ng-template>
  12. <ng-template pTemplate="body" let-rowData let-columns="columns">
  13. <tr>
  14. <td *ngFor="let col of columns">
  15. <span class="ui-column-title">{{col.header}}</span>
  16. {{rowData[col.field]}}
  17. </td>
  18. </tr>
  19. </ng-template>
  20. <ng-template pTemplate="summary">
  21. There are {{cars?.length}} cars
  22. </ng-template>
  23. </p-table>
  24.  

See the live example.

EmptyMessage

When there is no data, emptymessage template can be used to display a message.

  1. <p-table [value]="cars">
  2. <ng-template pTemplate="header">
  3. <tr>
  4. <th>Vin</th>
  5. <th>Year</th>
  6. <th>Brand</th>
  7. <th>Color</th>
  8. </tr>
  9. </ng-template>
  10. <ng-template pTemplate="body" let-car>
  11. <tr>
  12. <td>{{car.vin}}</td>
  13. <td>{{car.year}}</td>
  14. <td>{{car.brand}}</td>
  15. <td>{{car.color}}</td>
  16. </tr>
  17. </ng-template>
  18. <ng-template pTemplate="emptymessage" let-columns>
  19. <tr>
  20. <td [attr.colspan]="columns.length">
  21. No records found
  22. </td>
  23. </tr>
  24. </ng-template>
  25. </p-table>
  26.  

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.

  1. <p-table [value]="cars" [loading]="loading">
  2. <ng-template pTemplate="header">
  3. <tr>
  4. <th>Vin</th>
  5. <th>Year</th>
  6. <th>Brand</th>
  7. <th>Color</th>
  8. </tr>
  9. </ng-template>
  10. <ng-template pTemplate="body" let-car>
  11. <tr>
  12. <td>{{car.vin}}</td>
  13. <td>{{car.year}}</td>
  14. <td>{{car.brand}}</td>
  15. <td>{{car.color}}</td>
  16. </tr>
  17. </ng-template>
  18. </ng-template>
  19. </p-table>
  20.  
  1. export class DataTableDemo implements OnInit {
  2. loading: boolean;
  3. cars: Car[];
  4. constructor(private carService: CarService) { }
  5. ngOnInit() {
  6. this.loading = true;
  7. setTimeout(() => {
  8. this.carService.getCarsSmall().then(cars => this.cars = cars);
  9. this.loading = false;
  10. }, 1000);
  11. }
  12. }
  13.  

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.

  1. <p-table [columns]="cols" [value]="cars">
  2. <ng-template pTemplate="colgroup" let-columns>
  3. <colgroup>
  4. <col>
  5. <col>
  6. <col>
  7. <col style="background-color:#FFD54F !important">
  8. </colgroup>
  9. </ng-template>
  10. <ng-template pTemplate="header" let-columns>
  11. <tr>
  12. <th *ngFor="let col of columns">
  13. {{col.header}}
  14. </th>
  15. </tr>
  16. </ng-template>
  17. <ng-template pTemplate="body" let-rowData let-columns="columns">
  18. <tr [ngClass]="rowData.year > 2010 ? 'old-car' : null">
  19. <td *ngFor="let col of columns" [ngClass]="rowData[col.field] < 2000 ? 'very-old-car' : null">
  20. {{rowData[col.field]}}
  21. </td>
  22. </tr>
  23. </ng-template>
  24. </p-table>
  25.  

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

NameTypeDefaultDescription
valuearraynullAn array of objects to display.
columnsarraynullAn array of objects to represent dynamic columns.
frozenColumnsarraynullAn array of objects to represent dynamic columns that are frozen.
frozenValuearraynullAn array of objects to display as frozen.
stylestringnullInline style of the component.
styleClassstringnullStyle class of the component.
tableStyleanynullInline style of the table.
tableStyleClassstringnullStyle class of the table.
paginatorbooleanfalseWhen specified as true, enables the pagination.
rowsnumbernullNumber of rows to display per page.
firstnumber0Index of the first row to be displayed.
totalRecordsnumbernullNumber of total records, defaults to length of value when not defined.
pageLinksnumbernullNumber of page links to display in paginator.
rowsPerPageOptionsarraynullArray of integer values to display inside rows per page dropdown of paginator
alwaysShowPaginatorbooleantrueWhether to show it even there is only one page.
paginatorPositionstringbottomPosition of the paginator, options are "top","bottom" or "both".
currentPageReportTemplatestring{currentPage} of {totalPages}Text to display the current page information.
showCurrentPageReportbooleanfalseWhether to display current page report.
sortModestringsingleDefines whether sorting works on single column or on multiple columns.
sortFieldstringnullName of the field to sort data by default.
sortOrdernumber1Order to sort when default sorting is enabled.
multiSortMetaarraynullAn array of SortMeta objects to sort the data by default in multiple sort mode.
rowGroupModestringnullType of the row grouping, valid values are "subheader" and "rowspan".
defaultSortOrdernumber1Sort order to use when an unsorted column gets sorted by user interaction.
customSortbooleanfalseWhether to use the default sorting or a custom one using sortFunction.
sortFunctionfunctionnullA function to implement custom sorting, refer to sorting section for details.
selectionModestringnullSpecifies the selection mode, valid values are "single" and "multiple".
selectionanynullSelected row in single mode or an array of values in multiple mode.
contextMenuSelectionanynullSelected row with a context menu.
contextMenuSelectionModestringseparateDefines 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.
dataKeystringnullA property to uniquely identify a record in data.
metaKeySelectionbooleantrueDefines whether metaKey is should be considered for the selection. On touch enabled devices, metaKeySelection is turned off automatically.
rowTrackByFunctionnullFunction to optimize the dom operations by delegating to ngForTrackBy, default algoritm checks for object identity.
lazybooleanfalseDefines if data is loaded and interacted with in lazy manner.
lazyLoadOnInitbooleantrueWhether to call lazy loading on initialization.
compareSelectionBystringdeepEqualsAlgorithm to define if a row is selected, valid values are "equals" that compares by reference and "deepEquals" that compares all fields.
csvSeparatorstring,Character to use as the csv separator.
exportFilenamestringdownloadName of the exported file.
filtersarraynullAn array of FilterMetadata objects to provide external filters.
filterDelaynumber300Delay in milliseconds before filtering the data.
globalFilterFieldsarraynullAn array of fields as string to use in global filtering.
expandedRowKeys{[s: string]: boolean;}nullMap instance to keep the expanded rows where key of the map is the data key of the row.
rowExpandModestringmultipleWhether multiple rows can be expanded at any time. Valid values are "multiple" and "single".
scrollablebooleanfalseWhen specifies, enables horizontal and/or vertical scrolling.
scrollHeightstringnullHeight of the scroll viewport in fixed pixels, percentage or a calc expression.
virtualScrollbooleanfalseWhether the data should be loaded on demand during scroll.
virtualScrollDelaynumber150Delay in virtual scroll before doing a call to lazy load.
virtualRowHeightnumber28Height of a row to use in calculations of virtual scrolling.
frozenWidthstringnullWidth of the frozen columns container.
responsivebooleanfalseDefines if the columns should be stacked in smaller screens.
contextMenuContextMenunullLocal ng-template varilable of a ContextMenu.
resizableColumnsbooleanfalseWhen enabled, columns can be resized using drag and drop.
columnResizeModestringfitDefines whether the overall table width should change on column resize, valid values are "fit" and "expand".
reorderableColumnsbooleanfalseWhen enabled, columns can be reordered using drag and drop.
loadingbooleanfalseDisplays a loader to indicate data load is in progress.
loadingIconstringfa-circle-o-notchThe icon to show while indicating data load is in progress.
showLoaderbooleantrueWhether to show the loading mask when loading property is true.
rowHoverbooleanfalseAdds hover effect to rows without the need for selectionMode.
paginatorDropdownAppendToanynullTarget element to attach the paginator dropdown overlay, valid values are "body" or a local ng-template variable of another element.
autoLayoutbooleanfalseWhether the cell widths scale according to their content or not.
resetPageOnSortbooleantrueWhen true, resets paginator to first page after sorting.
exportFunctionfunctionnullA function to implement custom export. Need to return string value. event.data: Field data. event.field: Column field.
stateKeystringnullUnique identifier of a stateful table to use in state storage.
stateStoragestringsessionDefines where a stateful table keeps its state, valid values are "session" for sessionStorage and "local" for localStorage.
editModestringcellDefines the editing mode, valid values are "cell" and "row".
editingRowKeys{[s: string]: boolean;}nullMap instance to keep the rows being edited where key of the map is the data key of the row.

Events

NameParametersDescription
onRowSelectevent.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.
onRowUnselectevent.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.
onPageevent.first: Index of first record in page event.rows: Number of rows on the pageCallback to invoke when pagination occurs.
onSortevent.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.
onFilterevent.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.
onLazyLoadevent.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 availableCallback to invoke when paging, sorting or filtering happens in lazy mode.
onRowExpandevent.originalEvent: Browser event data: Row data to expand.Callback to invoke when a row is expanded.
onRowCollapseevent.originalEvent: Browser event data: Row data to collapse.Callback to invoke when a row is collapsed.
onContextMenuSelectevent.originalEvent: Browser event event.data: Selected dataCallback to invoke when a row is selected with right click.
onColResizeevent.element: Resized column header event.delta: Change of width in number of pixelsCallback to invoke when a column is resized.
onColReorderevent.dragIndex: Index of the dragged column event.dropIndex: Index of the dropped column event.columns: Columns array after reorderCallback to invoke when a column is reordered.
onRowReorderevent.dragIndex: Index of the dragged row event.dropIndex: Index of the drop locationCallback to invoke when a row is reordered.
onEditInitevent.column: Column object of the cell event.data: Row dataCallback to invoke when a cell switches to edit mode.
onEditCompleteevent.column: Column object of the cell event.data: Row data event.index: Row indexCallback to invoke when cell edit is completed.
onEditCancelevent.column: Column object of the cell event.data: Row data event.index: Row indexCallback to invoke when cell edit is cancelled with escape key.
onHeaderCheckboxToggleevent.originalEvent: Browser event event.checked: State of the header checkboxCallback to invoke when state of header checkbox changes.
onStateSavestate: Table stateCallback to invoke table state is saved.
onStateRestorestate: Table stateCallback to invoke table state is restored.

Methods

NameParametersDescription
reset-Resets sort, filter and paginator state.
clearState-Clears table state.
exportCSVconfig?.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.

NameElement
ui-tableContainer element.
ui-table-captionCaption element.
ui-table-summarySection section.
ui-sortable-columnSortable column header.
ui-table-scrollable-headerContainer of header in a scrollable table.
ui-table-scrollable-bodyContainer of body in a scrollable table.
ui-table-scrollable-footerContainer of footer in a scrollable table.
ui-table-responsiveContainer element of a responsive datatable.
ui-table-loadingLoader mask.
ui-table-loading-contentLoader content.
ui-table-wrapperLoader content.
ui-table-scrollable-wrapperLoader content.
ui-column-resizer-helperVertical resize indicator bar. To show the resize indicator bar set the "background-color" property.
ui-table-reorder-indicator-topTop indicator of column reordering.
ui-table-reorder-indicator-topBottom indicator of column reordering.

Dependencies

None.

Source

View on GitHub

  1. <h3 class="first">Basic</h3>
  2. <p-table [value]="cars">
  3. <ng-template pTemplate="header">
  4. <tr>
  5. <th>Vin</th>
  6. <th>Year</th>
  7. <th>Brand</th>
  8. <th>Color</th>
  9. </tr>
  10. </ng-template>
  11. <ng-template pTemplate="body" let-car>
  12. <tr>
  13. <td>{{car.vin}}</td>
  14. <td>{{car.year}}</td>
  15. <td>{{car.brand}}</td>
  16. <td>{{car.color}}</td>
  17. </tr>
  18. </ng-template>
  19. </p-table>
  20. <h3>Dynamic Columns</h3>
  21. <p-table [columns]="cols" [value]="cars">
  22. <ng-template pTemplate="header" let-columns>
  23. <tr>
  24. <th *ngFor="let col of columns">
  25. {{col.header}}
  26. </th>
  27. </tr>
  28. </ng-template>
  29. <ng-template pTemplate="body" let-rowData let-columns="columns">
  30. <tr>
  31. <td *ngFor="let col of columns">
  32. {{rowData[col.field]}}
  33. </td>
  34. </tr>
  35. </ng-template>
  36. </p-table>
  37.  
  1. export class TableDemo implements OnInit {
  2. cars: Car[];
  3. cols: any[];
  4. constructor(private carService: CarService) { }
  5. ngOnInit() {
  6. this.carService.getCarsSmall().then(cars => this.cars = cars);
  7. this.cols = [
  8. { field: 'vin', header: 'Vin' },
  9. {field: 'year', header: 'Year' },
  10. { field: 'brand', header: 'Brand' },
  11. { field: 'color', header: 'Color' }
  12. ];
  13. }
  14. }
  15.