Как объединить столбцы в p-таблице с динамическими столбцами - PullRequest
0 голосов
/ 18 января 2019

Мой источник данных обслуживает файл данных json в следующем формате.

subjects.json

[
  {
    "subjectCode": "1111",
    "subjectTitle": "English Literature",
    "subjectGroup": "English",
    "status": "Available"
  },
  {
    "subjectCode": "2222",
    "subjectTitle": "Algebra III",
    "subjectGroup": "Mathematics",
    "status": "Not Available"
  }
]

Вот класс интерфейса, используемый для чтения файла данных.

subject.model.ts

export interface Subject {
    subjectCode: string;
    subjectTitle: string;
    subjectGroup: string;
    status: string;
}

и файл компонента

subject.component.ts

export class SubjectComponent implements OnInit {

    searchResults: Subject[];

    // lots of other stuff

}

По причинам, связанным с дизайном пользовательского интерфейса, мне нужно отобразить код темы и название темы в виде одного столбца в браузере. Это легко сделать, если я использовал статические столбцы.

subject.component.html со статическими столбцами

<p-table [columns]="cols" [value]="searchResults">
    <ng-template pTemplate="header" let-columns>
        <tr>
            <th>Subject</th>
            <th>Group</th>
            <th>Status</th>          
        </tr>
     </ng-template>
     <ng-template pTemplate="body" let-rowData>
         <tr>
            <td>{{rowData.subjectCode}}&nbsp;{{rowData.subjectTitle}}</td>
            <td>{{rowData.subjectGroup}}</td>
            <td>{{rowData.status}}</td>
         </tr>
     </ng-template>
</p-table>

Однако, когда я попытался сделать то же самое с динамическими столбцами, я не могу найти способ сделать это с параметрами {{rowData [col.field]}}, которые использует динамический столбец, и я не могу найти упоминания о как это сделать в документации PrimeNG.

изменен subject.component.ts для использования динамических столбцов

export class SubjectComponent implements OnInit {

    searchResults: Subject[];

    // table columns
    this.cols = [
        { field: 'subjectCode', header: 'Subject code'},
        { field: 'subjectTitle', header: 'Subject title'},
        { field: 'subjectGroup', header: 'Group'},
        { field: 'status', header: 'Status'}
    ];

// lots of other stuff
}

измененный subject.component.html с динамическими столбцами

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

Как объединить предметный код и заголовок из интерфейса в один столбец в p-таблице, используя динамические столбцы?

1 Ответ

0 голосов
/ 19 января 2019

Вы можете проверить индекс столбца или поле столбца, чтобы пропустить визуализацию столбца, например this :

<p-table [columns]="cols" [value]="data">
    <ng-template pTemplate="header" let-columns>
        <tr>
            <ng-container *ngFor="let col of columns; let i = index">
                <th *ngIf="i != 1">
                    {{col.header}}
                    <p-sortIcon [field]="col.field"></p-sortIcon>
                </th>
            </ng-container>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-rowData let-columns="columns">
        <tr>
            <ng-container *ngFor="let col of columns; let i = index">
                <td *ngIf="i == 0">
                    {{ rowData[col.field] + ' ' + rowData[columns[i + 1].field] }}
                </td>
                <td *ngIf="i > 1">
                    {{rowData[col.field]}}
                </td>
            </ng-container>
        </tr>
    </ng-template>
</p-table>

или как это:

<p-table [columns]="cols" [value]="data">
    <ng-template pTemplate="header" let-columns>
        <tr>
            <ng-container *ngFor="let col of columns">
                <th *ngIf="col.field != 'subjectTitle'">
                    {{col.header}}
                    <p-sortIcon [field]="col.field"></p-sortIcon>
                </th>
            </ng-container>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-rowData let-columns="columns">
        <tr>
            <ng-container *ngFor="let col of columns; let i = index">
                <td *ngIf="col.field == 'subjectCode'">
                    {{ rowData.subjectCode + ' ' + rowData.subjectTitle }}
                </td>
                <td *ngIf="col.field != 'subjectTitle' && col.field != 'subjectCode'">
                    {{rowData[col.field]}}
                </td>
            </ng-container>
        </tr>
    </ng-template>
</p-table>
...