首页 > 解决方案 > PrimeNg排序

问题描述

我正在使用 primeNg <p-table>。我想实现数据排序。我所做的是下面

排序.HTML

<p-table [columns]="cols" [value]="documents">
    <ng-template pTemplate="header" let-columns>
        <tr>
            <th *ngFor="let col of columns" [pSortableColumn]="col.field">
                {{col.header}}
                <p-sortIcon [field]="col.field"></p-sortIcon>
            </th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-doc>
        <tr>
            <td>
                {{doc.sName}}
            </td>

        <td>
                {{doc.sYear}}
            </td>
        <td>
                {{doc.sAge}}
            </td>
        <td>
                {{doc.sColor}}
            </td>        
        </tr>
    </ng-template>
</p-table>

排序.ts

this.cols = [
            { field: 'name', header: 'Name' },
            { field: 'year', header: 'Year' },
            { field: 'age', header: 'Age' },
            { field: 'color', header: 'Color' }
        ];

ngOnInit(){
    //made a service call and got data for

this.documents=[{
"sName":"Jhon",
"sYear":"1994",
"sAge":"20",
"sColor":"Red"
},
{
"sName":"Sam",
"sYear":"1996",
"sAge":"25",
"sColor":"Red"
},
{
"sName":"Anna",
"sYear":"1991",
"sAge":"21",
"sColor":"Green"
},
{
"sName":"Jhon",
"sYear":"1999",
"sAge":"25",
"sColor":"Blue"
},
{
"sName":"Betty",
"sYear":"1993",
"sAge":"35",
"sColor":"Red"
}]
}

到目前为止,只有Name字段正在排序,如何在其他列中也实现排序?我使用[pSortableColumn]但列没有得到排序,我错过了某个点。你能指导我哪里错了吗?

PS:我不能用<p-dataTable>

标签: angularprimengprimeng-datatable

解决方案


对于使用 Turbo 表/具有固定列的 p 表进行排序,请尝试以下代码

                <p-table #dt [value]="data">
                <ng-template pTemplate="header">
                    <tr>
                        <th [pSortableColumn]="'Name'">Name
                            <p-sortIcon [field]="'Name'"></p-sortIcon>
                        </th>
                        <th [pSortableColumn]="'Age'">Age
                            <p-sortIcon [field]="'Age'"></p-sortIcon>
                        </th>
                        <th [pSortableColumn]="'Height'">Height
                            <p-sortIcon [field]="'Height'"></p-sortIcon>
                        </th>
                    </tr>
                </ng-template>
                <ng-template pTemplate="body" let-col>
                    <tr>
                        <td>{{col.Name}}</td>
                        <td>{{col.Age}}</td>
                        <td>{{col.Height}}</td>
                    </tr>
                </ng-template>
            </p-table>

推荐阅读