PrimeNG之DataTable

--數據表顯示在表格格式數據。html

Basic

Import

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

source

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

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

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

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

Getting Started(入門)

數據表須要一個數組做爲值對象和列p-column組件定義。在整個樣本,汽車接口具備VIN,品牌,年份和顏色屬性是用來定義一個對象是由數據表中顯示。汽車是由一個carservice鏈接到服務器去取車的Promise.json

 

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

 

 

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

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

 下面的示例數據表有4列,從服務檢索數據的初始化。數組

export class DataTableDemo implements OnInit {

    cars: Car[];

    constructor(private carService: CarService) { }

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

汽車列表綁定到值的屬性和列使用p-column組件定義。服務器

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

 Column Component

列組件定義了各類選項以指定相應的功能。angular2

Attributes

Nameapp

  Type Default Description
field string null Property of a row data.
sortField string null Property of a row data used for sorting, defaults to field.
header string null Header text of a column.
footer string null Footer text of a column.
sortable any false Defines if a column is sortable.
sortFunction function null Sort function for custom sorting.
editable boolean false Defines if a column is editable.
filter boolean false Defines if a column can be filtered.
filterMatchMode string null Defines filterMatchMode; "startsWith", "contains", "endsWidth", "equals" and "in".
filterPlaceholder string null Defines placeholder of the input fields.
rowspan string null Number of rows to span for grouping.
colspan string null Number of columns to span for grouping.
style string null Inline style of the column.
styleClass string null Style class of the column.
tableStyle string null Inline style of the table element.
tableStyleClass string null Style class of the table element.
hidden boolean false Controls visiblity of the column.
expander boolean false Displays an icon to toggle row expansion.
selectionMode string null Defines column based selection mode, options are "single" and "multiple".
frozen boolean false Whether the column is fixed in horizontal scrolling or not.

 

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

 

 

Dynamic Colums

列能夠被實例化使用數組以及ngfor迭代。dom

export class DataTableDemo implements OnInit {

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

    constructor(private carService: CarService) { }

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

 

 

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

 

 Templates

一個相應的行字段的數據顯示爲默認的單元格的內容,能夠自定義模板,使用隱式變量傳遞到ng模板列定義和當前行數據rowData財產。在目前除了指數可使用可選的rowIndex變量訪問。相似地,自定義內容能夠放在列的頁眉和頁腳上,模板。ide

ng-template內的列必須用ptemplate指令來代表ng-template屬於的類型。可能的值是「頭」、「體」和「頁腳」。性能

 

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

 

 行的索引在ng-template可用。ui

 

 <p-column>
        <ng-template let-car="rowData" let-i="rowIndex" pTemplate="body">
            <button type="button" pButton (click)="selectCar(i)" icon="fa-search"></button>
        </ng-template>
  </p-column>

 

  example

Facets

頁眉和頁腳是能夠顯示自定義內容的兩個部分。

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

 

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

 Column Grouping

列能夠被分組在頁眉和頁腳使用headercolumngroup和footercolumngroup組件包含行與列。模板也支持內分組列。

<p-dataTable [value]="sales">
    <p-headerColumnGroup>
        <p-row>
            <p-column header="Brand" rowspan="3"></p-column>
            <p-column header="Sale Rate" colspan="4"></p-column>
        </p-row>
        <p-row>
            <p-column header="Sales" colspan="2"></p-column>
            <p-column header="Profits" colspan="2"></p-column>
        </p-row>
        <p-row>
            <p-column header="Last Year"></p-column>
            <p-column header="This Year"></p-column>
            <p-column header="Last Year"></p-column>
            <p-column header="This Year"></p-column>
        </p-row>
    </p-headerColumnGroup>
    
    <p-column field="brand"></p-column>
    <p-column field="lastYearSale"></p-column>
    <p-column field="thisYearSale"></p-column>
    <p-column field="lastYearProfit"></p-column>
    <p-column field="thisYearProfit"></p-column>
    
    <p-footerColumnGroup>
        <p-row>
            <p-column footer="Totals:" colspan="3"></p-column>
            <p-column footer="$506,202"></p-column>
            <p-column footer="$531,020"></p-column>
        </p-row>
    </p-footerColumnGroup>
</p-dataTable>

 

 Row Grouping

行能夠按一個單獨的分組的行或使用的行。在這兩種狀況下,數據必須由分組字段首先進行排序。

<p-dataTable [value]="cars1" sortField="brand" rowGroupMode="subheader" groupField="brand">
    <p-header>Subheader</p-header>
    <ng-template pTemplate="rowgroupheader" let-rowData>{{rowData['brand']}}</ng-template>
    <p-column field="color" header="Color"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="vin" header="Vin"></p-column>
</p-dataTable>

<p-dataTable [value]="cars2" sortField="brand" rowGroupMode="rowspan">
    <p-header>RowSpan</p-header>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="vin" header="Vin"></p-column>
</p-dataTable>

 

 一組知名度可切換使用的圖標放在旁邊,用expandablerowgroups屬性組的名稱。默認狀況下,全部的組都崩潰了,expandadrowgroups財產須要填充組字段值顯示特定羣體擴展默認。

 

<p-dataTable [value]="cars" sortField="brand" rowGroupMode="subheader" groupField="brand" expandableRowGroups="true">
    <p-header>Subheader</p-header>
    <ng-template pTemplate="rowgroup" let-rowData>{{rowData['brand']}}</ng-template>
    <p-column field="color" header="Color"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="vin" header="Vin"></p-column>
</p-dataTable>

 

 一個排的頁腳可使用rowgroupfooter ng模板定義。

 1 <p-dataTable [value]="cars" sortField="brand" rowGroupMode="subheader" groupField="brand" expandableRowGroups="true"
 2         [sortableRowGroup]="false">
 3     <p-header>Toggleable Row Groups with Footers</p-header>
 4     <ng-template pTemplate="rowgroupheader" let-rowData>{{rowData['brand']}}</ng-template>
 5     <p-column field="color" header="Color"></p-column>
 6     <p-column field="year" header="Year"></p-column>
 7     <p-column field="vin" header="Vin"></p-column>
 8     <p-column field="price" header="Price">
 9         <ng-template let-col let-car="rowData" pTemplate="body">
10             <span>{{car[col.field] | currency:'USD':true:'.0-0'}}</span>
11         </ng-template>
12     </p-column>
13     <ng-template pTemplate="rowgroupfooter" let-car>
14         <td colspan="3" style="text-align:right">Total Price</td>
15         <td>{{calculateGroupTotal(car['brand']) | currency:'USD':true:'.0-0' }}</td>
16     </ng-template>
17 </p-dataTable>
View Code

 

 單擊行組分類根據組字段的數據,你可使用sortablerowgroup財產這一行爲控制

demo code

export class DataTableRowGroupDemo implements OnInit {

    cars1: Car[];
    
    cars2: Car[];
    
    cars3: Car[];
    
    constructor(private carService: CarService) {}

    ngOnInit() {
        this.carService.getCarsMedium().then(cars => this.cars1 = cars);
        this.carService.getCarsMedium().then(cars => this.cars2 = cars);
        this.carService.getCarsMedium().then(cars => this.cars3 = cars);
    }
    
    calculateGroupTotal(brand: string) {
        let total = 0;
        
        if(this.cars1) {
            for(let car of this.cars1) {
                if(car.brand === brand) {
                    total += car.price;
                }
            }
        }

        return total;
    }
}
DataTableRowGroupDemo.ts
<p-dataTable [value]="cars1" sortField="brand" rowGroupMode="subheader" groupField="brand" expandableRowGroups="true"
        [sortableRowGroup]="false">
    <p-header>Toggleable Row Groups with Footers</p-header>
    <ng-template pTemplate="rowgroupheader" let-rowData>{{rowData['brand']}}</ng-template>
    <p-column field="color" header="Color"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="price" header="Price">
        <ng-template let-col let-car="rowData" pTemplate="body">
            <span>{{car[col.field] | currency:'USD':true:'.0-0'}}</span>
        </ng-template>
    </p-column>
    <ng-template pTemplate="rowgroupfooter" let-car>
        <td colspan="3" style="text-align:right">Total Price</td>
        <td>{{calculateGroupTotal(car['brand']) | currency:'USD':true:'.0-0' }}</td>
    </ng-template>
</p-dataTable>

<p-dataTable [value]="cars2" sortField="brand" rowGroupMode="subheader" groupField="brand" [style]="{'margin-top':'50px'}">
    <p-header>Subheader</p-header>
    <ng-template pTemplate="rowgroupheader" let-rowData>{{rowData['brand']}}</ng-template>
    <p-column field="color" header="Color" sortable="true"></p-column>
    <p-column field="year" header="Year" sortable="true"></p-column>
    <p-column field="vin" header="Vin" sortable="true"></p-column>
</p-dataTable>

<p-dataTable [value]="cars3" sortField="brand" rowGroupMode="rowspan" [style]="{'margin-top':'50px'}">
    <p-header>RowSpan</p-header>
    <p-column field="brand" header="Brand" sortable="true"></p-column>
    <p-column field="color" header="Color" sortable="true"></p-column>
    <p-column field="year" header="Year" sortable="true"></p-column>
    <p-column field="vin" header="Vin" sortable="true"></p-column>
</p-dataTable>
DataTableRowGroupDemo.html

 

 

Paginator

分頁的設置頁面屬性來啓用,行屬性定義每一個頁面的行數和頁面鏈接,指定要顯示的數頁連接。

 

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

 demo code

export class DataTablePaginatorDemo implements OnInit {

    cars: Car[];

    constructor(private carService: CarService) { }

    ngOnInit() {
        this.carService.getCarsMedium().then(cars => this.cars = cars);
    }
}
DataTablePaginatorDemo.ts
<p-dataTable [value]="cars" [rows]="10" [paginator]="true" [pageLinks]="3" [rowsPerPageOptions]="[5,10,20]">
    <p-header>List of Cars</p-header>
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>
DataTablePaginatorDemo.html

 

Sorting

簡單使列對象排序的性能足以讓一列排序。屬性時要使用的默認排序字段,可使用sortfield定製。

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

 

 默認狀況下,在單擊列執行排序。作的多字段分類,設置「多」SortMode屬性和使用元鍵點擊另外一列。

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

 

 若是你想顯示錶按默認最初的負載,使用單一模式的sortfield SortOrder屬性。

 

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

 

 在multiple mode,使用multisortmeta屬性和約束sortmeta對象數組。在多個模式,使用multisortmeta屬性和約束sortmeta對象數組。

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

 

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

 

自定義排序,將排序選項,自定義,定義一個sortfunction分類列表。

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

 demo code

export class DataTableSortDemo implements OnInit {

    cars1: Car[];
    
    cars2: Car[];

    constructor(private carService: CarService) { }

    ngOnInit() {
        this.carService.getCarsSmall().then(cars => this.cars1 = cars);
        this.carService.getCarsSmall().then(cars => this.cars2 = cars);
    }
}
DataTableSortDemo.ts

 

<h3 class="first">Single Column</h3>
<p-dataTable [value]="cars1">
    <p-column field="vin" header="Vin" [sortable]="true"></p-column>
    <p-column field="year" header="Year" [sortable]="true"></p-column>
    <p-column field="brand" header="Brand" [sortable]="true"></p-column>
    <p-column field="color" header="Color" [sortable]="true"></p-column>
</p-dataTable>

<h3>Multiple Columns</h3>
<p-dataTable [value]="cars2" sortMode="multiple">
    <p-column field="vin" header="Vin" [sortable]="true"></p-column>
    <p-column field="year" header="Year" [sortable]="true"></p-column>
    <p-column field="brand" header="Brand" [sortable]="true"></p-column>
    <p-column field="color" header="Color" [sortable]="true"></p-column>
</p-dataTable>
DataTableSortDemo.html

 

Filtering

經過在列上設置篩選器屬性爲True,啓用了篩選。默認的匹配模式是「startsWith」,這能夠被配置爲使用filtermatchmode屬性,也接受"contains", "endsWith", "equals" and "in"。

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

一個可選的全球過濾功能可與相同的關鍵字搜索的全部領域,使這個地方輸入組件的KeyUp事件會聽了過濾和綁定的局部ng模板變量名爲全球的濾波特性。

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

默認狀況下,輸入字段用做過濾器元素,而且可使用模板進行自定義。它是用在過濾元件改變回調經過值調用DataTable的過濾方法重要,場和matchmode性質。

<p-column field="brand" header="Brand (Custom)" [filter]="true" [style]="{'overflow':'visible'}" filterMatchMode="equals">
    <ng-template pTemplate="filter" let-col>
        <p-dropdown [options]="brands" [style]="{'width':'100%'}" (onChange)="dt.filter($event.value,col.field,col.filterMatchMode)" styleClass="ui-column-filter"></p-dropdown>
    </ng-template>
</p-column>

 demo code

export class DataTableFilterDemo implements OnInit {

    cars: Car[];
    
    brands: SelectItem[];
    
    colors: SelectItem[];
    
    constructor(private carService: CarService) {}

    ngOnInit() {
        this.carService.getCarsMedium().then(cars => this.cars = cars);
        
        this.brands = [];
        this.brands.push({label: 'All Brands', value: null});
        this.brands.push({label: 'Audi', value: 'Audi'});
        this.brands.push({label: 'BMW', value: 'BMW'});
        this.brands.push({label: 'Fiat', value: 'Fiat'});
        this.brands.push({label: 'Honda', value: 'Honda'});
        this.brands.push({label: 'Jaguar', value: 'Jaguar'});
        this.brands.push({label: 'Mercedes', value: 'Mercedes'});
        this.brands.push({label: 'Renault', value: 'Renault'});
        this.brands.push({label: 'VW', value: 'VW'});
        this.brands.push({label: 'Volvo', value: 'Volvo'});
        
        this.colors = [];
        this.colors.push({label: 'White', value: 'White'});
        this.colors.push({label: 'Green', value: 'Green'});
        this.colors.push({label: 'Silver', value: 'Silver'});
        this.colors.push({label: 'Black', value: 'Black'});
        this.colors.push({label: 'Red', value: 'Red'});
        this.colors.push({label: 'Maroon', value: 'Maroon'});
        this.colors.push({label: 'Brown', value: 'Brown'});
        this.colors.push({label: 'Orange', value: 'Orange'});
        this.colors.push({label: 'Blue', value: 'Blue'});
    }
}
DataTableFilterDemo.ts

 

<div class="ui-widget-header" style="padding:4px 10px;border-bottom: 0 none">
    <i class="fa fa-search" style="margin:4px 4px 0 0"></i>
    <input #gb type="text" pInputText size="50" placeholder="Global Filter">
</div>
<p-dataTable [value]="cars" [rows]="10" [paginator]="true" [globalFilter]="gb" #dt>
    <p-header>List of Cars</p-header>
    <p-column field="vin" header="Vin (startsWith)" [filter]="true" filterPlaceholder="Search"></p-column>
    <p-column field="year" header="Year ({{yearFilter||'No Filter'}}" [filter]="true" filterMatchMode="equals">
        <ng-template pTemplate="filter" let-col>
            <i class="fa fa-close" (click)="yearFilter=null;dt.filter(null,col.field,col.filterMatchMode)"></i>
            <p-slider [style]="{'width':'100%','margin-top':'8px'}" [(ngModel)]="yearFilter" [min]="1970" [max]="2010" (onSlideEnd)="dt.filter($event.value,col.field,col.filterMatchMode)"></p-slider>
        </ng-template>
    </p-column>
    <p-column field="brand" header="Brand (Custom)" [filter]="true" [style]="{'overflow':'visible'}" filterMatchMode="equals">
        <ng-template pTemplate="filter" let-col>
            <p-dropdown [options]="brands" [style]="{'width':'100%'}" (onChange)="dt.filter($event.value,col.field,col.filterMatchMode)" styleClass="ui-column-filter"></p-dropdown>
        </ng-template>
    </p-column>
    <p-column field="color" header="Color (Custom)" [filter]="true" filterMatchMode="in" [style]="{'overflow':'visible'}">
        <ng-template pTemplate="filter" let-col>
            <p-multiSelect [options]="colors" defaultLabel="All Colors" (onChange)="dt.filter($event.value,col.field,col.filterMatchMode)" styleClass="ui-column-filter"></p-multiSelect>
        </ng-template>
    </p-column>
</p-dataTable>
DataTableFilterDemo.html

 

Selection

DataTable提供一排點擊單個和多個模式的選擇。選定行必然選擇屬性和onrowselect onrowunselect事件提供了可選的回調。另外基於列的選擇可使用單選按鈕或複選框使用一個特定的列SelectionMode爲。比較時,若是一行被選中,DataTable穿越影響性能結果的對象的全部屬性。建議定義一個DataKey屬性惟一標識一個記錄,避免深對象比較和提升性能。

在單一模式下,選擇綁定是一個對象引用。

export class DataTableDemo implements OnInit {

    cars: Car[];
    
    selectedCar: Car;

    constructor(private carService: CarService) { }

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

 

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

 

在多模式選擇的結合應該是一個數組和多個項目能夠選擇使用元鍵或切換單獨依靠metakeyselection屬性值是真正的默認值。觸摸功能的設備metakeyselection自動關閉。

export class DataTableDemo implements OnInit {

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

    constructor(private carService: CarService) { }

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

 

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

 

若是你喜歡一個單選按鈕或複選框,而不是連續點擊,使用一列的SelectionMode爲相反。如下數據表顯示在每一行的第一列的複選框,複選框中自動添加一個標題行切換選擇。

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

 

ContextMenu

DataTable與ContextMenu獨家整合。爲了將一個菜單數據表,定義了一個局部的菜單模板變量並將其綁定到DataTable的ContextMenu屬性。這使顯示的菜單時,行右鍵單擊。

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

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

 

Editing

Incell editing經過設置編輯屬性編輯對DataTable和列真正啓用。單擊單元格切換到編輯模式,點擊Enter鍵或單擊另外一個單元格將其切換回查看模式。

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

 

簡單的輸入字段做爲編輯元素默認狀況下,這能夠經過添加一個定製的ptemplate命名編輯。

<p-dataTable [value]="cars" [editable]="true">
    <p-column field="vin" header="Vin" [editable]="true"></p-column>
    <p-column field="year" header="Year" [editable]="true"></p-column>
    <p-column field="brand" header="Brand" [editable]="true" [style]="{'overflow':'visible'}">
        <ng-template let-col let-car="rowData" pTemplate="editor">
            <p-dropdown [(ngModel)]="car[col.field]" [options]="brands" [autoWidth]="false" [style]="{'width':'100%'}" required="true"></p-dropdown>
        </ng-template>
    </p-column>
    <p-column field="color" header="Color" [editable]="true"></p-column>
    <p-column field="saleDate" header="Sale Date" [editable]="true" [style]=" {'overflow':'visible' }">
        <ng-template let-col let-car="rowData" pTemplate="body">
             {{car[col.field]|date }}
        </ng-template>
        <ng-template let-col let-car="rowData" pTemplate="editor">
            <p-calendar [(ngModel)]="car[col.field]"></p-calendar>
        </ng-template>
    </p-column>
</p-dataTable>

 demo code

export class DataTableEditableDemo implements OnInit {

    cars: Car[];

    constructor(private carService: CarService) { }

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

 

<p-dataTable [value]="cars" [editable]="true">
    <p-column field="vin" header="Vin" [editable]="true"></p-column>
    <p-column field="year" header="Year" [editable]="true"></p-column>
    <p-column field="brand" header="Brand" [editable]="true" [style]="{'overflow':'visible'}">
        <ng-template let-col let-car="rowData" pTemplate="editor">
            <p-dropdown [(ngModel)]="car[col.field]" [options]="brands" [autoWidth]="false" [style]="{'width':'100%'}" required="true"></p-dropdown>
        </ng-template>
    </p-column>
    <p-column field="color" header="Color" [editable]="true"></p-column>
    <p-column field="saleDate" header="Sale Date" [editable]="true" [style]=" {'overflow':'visible' }">
        <ng-template let-col let-car="rowData" pTemplate="body">
             {{car[col.field]|date }}
        </ng-template>
        <ng-template let-col let-car="rowData" pTemplate="editor">
            <p-calendar [(ngModel)]="car[col.field]"></p-calendar>
        </ng-template>
    </p-column>
</p-dataTable>
DataTableEditableDemo.html

 

Expandable Rows

行擴展容許顯示特定行的詳細內容。要使用此功能,使expandablerows屬性,添加膨脹柱宣佈擴大內容提供ptemplate「rowexpansion」爲價值。

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

默認狀況下全部行倒塌,expandadrows財產須要填充的行數據實例來顯示特定行爲擴展默認。

Column Resize

列的大小可使用拖放設置resizablecolumns真實。有兩個大小調整模式;"fit" and "expand"。"fit"是默認的和總體的桌子的寬度並無改變時,一列大小。在"expand"模式下,表寬也隨着列寬度的變化而變化。oncolumnresize回調是經過調整列標題做爲參數。

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

Data Export

DataTable能夠以CSV格式的使用exportcsv()方法其數據輸出。

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

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

Scrolling

DataTable支持水平和垂直滾動經過定義scrollwidth和scrollheight選項分別。屬性能夠採起固定像素值或百分比來計算滾動視圖相對於DataTable母。樣品使用垂直滾動,頭下面是固定的,數據是可滾動的。在水平滾動,重要的是給固定寬度的列。

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

在水平滾動中,經過在列級上啓用凍結屬性,能夠固定某些列。

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

 

此外,virtualscroll模式能夠經過加載數據需求處理大型數據集時滾動。

Lazy Loading

懶模式是駕輕就熟地處理大型數據集,而不是加載整個數據,小塊數據是經過調用回調onlazyload每次分頁加載,排序和過濾發生。實現懶加載,使懶惰的屬性和提供利用onlazyload實際加載數據從遠程數據源的方法回調。onlazyload獲取一個事件對象包含有關如何負荷。它還指定行數的邏輯totalrecords作一個頁面配置投影查詢,頁面顯示UI假設實際上有記錄totalrecords規模雖然在現實中他們沒有在懶人模式重要,只顯示當前頁的記錄存在。

<p-dataTable [value]="cars" [scrollable]="true" [lazy]="true" (onLazyLoad)="loadData($event)" [totalRecords]="totalRecords">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>
loadData(event: LazyLoadEvent) {
    //event.first = First row offset
    //event.rows = Number of rows per page
    //event.sortField = Field name to sort in single sort mode
    //event.sortOrder = Sort order as number, 1 for asc and -1 for dec in single sort mode
    //multiSortMeta: An array of SortMeta objects used in multiple columns sorting. Each SortMeta has field and order properties.
    //filters: Filters object having field as key and filter value, filter matchMode as value
    //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
}

Responsive

數據表列顯示爲堆放在應答模式若是屏幕尺寸變得小於某個斷點值。此功能啓用響應設置爲true。

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

Overlays in Cells

Cells of datatable隱藏溢出默認狀況下,這能夠防止一部分像下拉菜單可正常顯示疊加。在這樣的狀況下,設置列的樣式以容許溢出。

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

 Immutable Mode

使用diff檢查若是DataTable來實現底層的數據發生了變化,這可能會下降性能,避免它一成不變的模式,確保您的數據的變化,如添加或刪除一個記錄都建立一個新數組引用。例如,添加項目時使用切片而不是剪接,添加項目時使用擴展運算符而不是推送方法。

Loading Status

DataTable具備承載性能,當啓用旋轉圖標顯示數據加載。

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

 

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);
    }
}

 Attributes

 

Name  Type Default Description
value array null An array of objects to display.
headerRows array null An array of column definitions for column grouping at header.
footerRows array null An array of column definitions for column grouping at footer.
rows number null Number of rows to display per page.
paginator boolean false When specified as true, enables the pagination.
totalRecords number null Number of total records, defaults to length of value when not defined.
pageLinks number null Number of page links to display in paginator.
rowsPerPageOptions array null Array of integer values to display inside rows per page dropdown of paginator
sortMode string single Defines whether sorting works on single column or on multiple columns.
sortField string null Name of the field to sort data by default.
sortOrder number null Order to sort the data by default.
multiSortMeta array null An array of SortMeta objects to sort the data by default in multiple sort mode.
rowGroupMode string null Type of the row grouping, valid values are "subheader" and "rowspan".
groupField string null Name of the field to group by in subheader row grouping mode.
sortableGroupRow boolean true Whether to sort the data if the row group subheader is clicked.
expandableRowGroups boolean false When enabled, adds a clickable icon at group header to expand or collapse the group.
expandedRowGroups array null Collection of group field values to show a group as expanded by default.
responsive boolean false Defines if the columns should be stacked in smaller screens.
selectionMode string null Specifies the selection mode, valid values are "single" and "multiple".
selection any null Selected row in single mode or an array of values in multiple mode.
editable boolean false Activates incell editing when enabled.
expandableRows boolean false Activates expandable rows feature when true.
expandedRows array null Collection of rows to display as expanded.
rowExpandMode string multiple Whether multiple rows can be expanded at any time. Valid values are "multiple" and "single".
globalFilter any null Reference of an input field to use as a global filter.
filterDelay number 300 Delay in milliseconds before filtering the data.
lazy boolean false Defines if data is loaded and interacted with in lazy manner.
resizableColumns boolean false When enabled, columns can be resized using drag and drop.
columnResizeMode boolean false Defines whether the overall table width should change on column resize, valid values are "fit" and "expand".
reorderableColumns boolean false When enabled, columns can be reordered using drag and drop.
scrollable boolean false When specifies, enables horizontal and/or vertical scrolling.
scrollHeight number/string null Height of the scroll viewport, can be pixel as a number or a percentage.
scrollWidth number/string null Width of the scroll viewport, can be pixel as a number or a percentage.
virtualScroll boolean false Whether the data should be loaded on demand during scroll.
style string null Inline style of the component.
styleClass string null Style class of the component.
contextMenu ContextMenu null Local ng-template varilable of a ContextMenu.
csvSeparator string , Character to use as the csv separator.
exportFilename string download Name of the exported file.
emptyMessage string No records found. Text to display when there is no data.
paginatorPosition string bottom Position of the paginator, options are "top","bottom" or "both".
rowTrackBy function null TrackBy function of ngFor directive used when rendering rows.
rowStyleClass function null Function that gets the row data and row index as parameters and returns a style class for the row.
rowHover boolean false Adds hover effect to rows without the need for selectionMode.
filters array null An array of FilterMetadata objects to provide external filters.
metaKeySelection boolean true Defines how multiple items can be selected, when true metaKey needs to be pressed to select or unselect an item and when set to false selection of each item can be toggled individually. On touch enabled devices, metaKeySelection is turned off automatically.
immutable boolean false Improves performance by avoiding diff checking, changes to value should be done in an immutable way on application side when immutable property is enabled.
dataKey string null A property to uniquely identify a record in data.
loading boolean false Displays a loader to indicate data load is in progress.

 

Events

 

 

Name  Parameters Description
onRowClick event.originalEvent: Browser event
event.data: Selected data
Callback to invoke when a row is clicked.
onRowSelect event.originalEvent: Browser event
event.data: Selected data
event.type: Type of selection, valid values are "row", "radiobutton" and "checkbox"
Callback to invoke when a row is selected.
onRowUnselect event.originalEvent: Browser event
event.data: Unselected data
event.type: Type of unselection, valid values are "row" and "checkbox"
Callback to invoke when a row is unselected with metakey.
onRowDblclick event.originalEvent: Browser event
event.data: Selected data
Callback to invoke when a row is selected with double clicked.
onHeaderCheckboxToggle event.originalEvent: Browser event
event.checked: State of the header checkbox
Callback to invoke when state of header checkbox changes.
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.
onLazyLoad event.first = First row offset
event.rows = Number of rows per page
event.sortField = Field name to sort with
event.sortOrder = Sort order as number, 1 for asc and -1 for dec
filters: FilterMetadata object having field as key and filter value, filter matchMode as value
Callback to invoke when paging, sorting or filtering happens in lazy mode.
onEditInit event.column: Column object of the cell
event.data: Row data
Callback to invoke when a cell switches to edit mode.
onEdit event.originalEvent: Browser event event.column: Column object of the cell
event.data: Row data
event.index: Row index
Callback to invoke when cell data is being edited.
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.
onPage event.first: Index of first record in page
event.rows: Number of rows on the page
Callback to invoke when pagination occurs.
onSort event.field: Field name of the sorted column
event.order: Sort order as 1 or -1
event.multisortmeta: Sort metadata in multi sort mode. See multiple sorting section for the structure of this object.
Callback to invoke when a column gets sorted.
onFilter event.filters: Filters object having a field as the property key and an object with value, matchMode as the property value. Callback to invoke when data is filtered.
onRowExpand 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.
onRowGroupExpand event.originalEvent: Browser event
group: Value of the group.
Callback to invoke when a row group is expanded.
onRowGroupCollapse event.originalEvent: Browser event
group: Value of the group.
Callback to invoke when a row group is collapsed.

 

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

 

 

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

Methods

 

Name  Parameters Description
reset - Resets sort, filter and paginator state.
exportCSV - Exports the data in csv format.
toggleRow data Toggles row expansion for given row data.

 

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

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

 

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

Styling

如下是結構式的類列表,對於主題類主題頁面訪問。

 

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

 參考資料:

https://www.primefaces.org/primeng/#/datatable

相關文章
相關標籤/搜索