본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

테이블

원문 보기 위키 갱신

테이블 (Table)

테이블 컴포넌트는 데이터를 행과 열로 이루어진 표 형태로 보여주는 PrimeNG의 대표적인 데이터 표시 컴포넌트예요. 기본 사용법부터 정렬, 필터링, 페이지네이션, 행 선택, 셀 편집처럼 실무에서 자주 쓰는 기능까지 폭넓게 다뤄요. 스크린 리더 접근성, 가상 스크롤, 컬럼 리사이즈, 행 그룹핑 같은 고급 기능 예제와 Props, Emits 같은 API 문서까지 함께 담겨 있어서 처음 배울 때부터 깊이 있게 참고하기 좋아요

출처: 문서

본문

접근성

스크린 리더 테이블의 기본 role은 table이에요. 헤더, 바디, 푸터 요소는 rowgroup을 사용하고, 행은 row role을, 헤더 셀은 columnheader, 바디 셀은 cell 역할을 사용해요. 정렬 가능한 헤더는 aria-sort 속성을 "ascending" 또는 "descending"으로 설정해서 사용해요. 테이블 행과 테이블 셀은 템플릿을 통해 결정되기 때문에, 사용자가 aria-posinset, aria-setsize, aria-label, aria-describedby 속성을 사용해 직접 지정해야 해요. 행 선택을 위한 내장 체크박스와 라디오버튼 컴포넌트는 checkbox와 radiobutton 역할을 사용해요. 이를 설명하는 라벨은 locale API의 aria.selectRow와 aria.unselectRow 속성에서 가져와요. 마찬가지로 헤더 체크박스는 selectAll과 unselectAll 키를 사용해요. 행이 선택되면 해당 행에 aria-selected가 true로 설정돼요. 행을 펼치거나 접는 요소는 aria-expanded와 aria-controls 속성을 가진 버튼이에요. 버튼을 설명하는 값은 locale API의 aria.expandRow와 aria.collapseRow 속성에서 도출돼요. 필터 메뉴 버튼은 버튼과 오버레이 사이의 관계를 정의하려고 aria-haspopup, aria-expanded, aria-controls에 더해 aria.showFilterMenu와 aria.hideFilterMenu 속성을 aria-label로 사용해요. 팝업 메뉴는 포커스가 오버레이 안에 유지되기 때문에 aria-modal과 함께 dialog 역할을 가져요. 연산자 드롭다운은 aria.filterOperator 속성을, 필터 제약 조건 드롭다운은 aria.filterConstraint 속성을 사용해요. 한편 규칙을 추가하는 버튼은 aria.addRule과 aria.removeRule 속성을 활용해요. 푸터 버튼도 마찬가지로 aria.clear와 aria.apply 속성을 사용해요. Column 컴포넌트의 filterInputProps를 사용하면 내장 필터 컴포넌트의 aria 라벨을 정의할 수 있고, 템플릿으로 커스텀 컴포넌트를 사용한다면 직접 aria 라벨을 정의할 수도 있어요. 편집 가능한 셀은 커스텀 템플릿을 사용하기 때문에, 필요하다면 aria 역할과 속성을 직접 관리해야 해요. 행 편집 컨트롤은 버튼 요소이고, aria-label로 aria.editRow, aria.cancelEdit, aria.saveEdit를 사용해요. Paginator는 Table 내부에서 사용되는 독립 컴포넌트예요. 접근성 기능에 대한 자세한 내용은 paginator 문서를 참고하세요. 키보드 지원 Table 내부에서 필터, 행 펼침, 편집 같은 용도로 사용되는 button 요소는 모두 탭으로 접근할 수 있고 space와 enter 키로 조작할 수 있어요. 정렬 가능한 헤더 키보드 지원 키 기능 tab 헤더 사이를 이동해요. enter 컬럼을 정렬해요. space 컬럼을 정렬해요. 필터 메뉴 키보드 지원 키 기능 tab 팝업 안의 요소 사이를 이동해요. escape 팝업을 숨겨요. enter 팝업을 열어요. 선택 키보드 지원 키 기능 tab 포커스를 첫 번째 선택된 행으로 이동하고, 없으면 첫 번째 행이 포커스를 받아요. up arrow 포커스를 이전 행으로 이동해요. down arrow 포커스를 다음 행으로 이동해요. enter metaKeySelection 설정에 따라 포커스된 행의 선택 상태를 토글해요. space metaKeySelection 설정에 따라 포커스된 행의 선택 상태를 토글해요. home 포커스를 첫 번째 행으로 이동해요. end 포커스를 마지막 행으로 이동해요. shift + down arrow 포커스를 다음 행으로 이동하고 선택 상태를 토글해요. shift + up arrow 포커스를 이전 행으로 이동하고 선택 상태를 토글해요. shift + space 가장 최근에 선택된 행과 포커스된 행 사이의 행들을 선택해요. control + shift + home 포커스된 행과 첫 번째 행까지의 모든 항목을 선택해요. control + shift + end 포커스된 행과 마지막 행까지의 모든 항목을 선택해요. control + a 모든 행을 선택해요.

기본

DataTable은 데이터를 표현할 컬럼 컴포넌트와 함께 표시할 컬렉션이 필요해요.

import { Component, OnInit, inject } from '@angular/core';
import { Table, TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-table [value]="products" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th>Code</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Quantity</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [ProductService]
})
export class TableBasicDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }
}

celledit-doc

셀 내부 편집은 pEditableColumn 디렉티브를 편집 가능한 셀에 추가하면 활성화돼요. 이 셀에는 편집 모드와 보기 모드에서 각각 사용할 입출력 템플릿을 정의하는 p-cellEditor 헬퍼 컴포넌트가 있어요.

import { Component, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { TableModule } from 'primeng/table';
import { InputTextModule } from 'primeng/inputtext';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-table [value]="products" dataKey="id" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th style="width:25%">Code</th>
                        <th style="width:25%">Name</th>
                        <th style="width:25%">Quantity</th>
                        <th style="width:25%">Price</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product let-editing="editing">
                    <tr>
                        <td [pEditableColumn]="product.code" pEditableColumnField="code">
                            <p-cellEditor>
                                <ng-template #input>
                                    <input pInputText type="text" [(ngModel)]="product.code" fluid />
                                </ng-template>
                                <ng-template #output>
                                    {{ product.code }}
                                </ng-template>
                            </p-cellEditor>
                        </td>
                        <td [pEditableColumn]="product.name" pEditableColumnField="name">
                            <p-cellEditor>
                                <ng-template #input>
                                    <input pInputText type="text" [(ngModel)]="product.name" required fluid />
                                </ng-template>
                                <ng-template #output>
                                    {{ product.name }}
                                </ng-template>
                            </p-cellEditor>
                        </td>
                        <td [pEditableColumn]="product.quantity" pEditableColumnField="quantity">
                            <p-cellEditor>
                                <ng-template #input>
                                    <input pInputText [(ngModel)]="product.quantity" fluid />
                                </ng-template>
                                <ng-template #output>
                                    {{ product.quantity }}
                                </ng-template>
                            </p-cellEditor>
                        </td>
                        <td [pEditableColumn]="product.price" pEditableColumnField="price">
                            <p-cellEditor>
                                <ng-template #input>
                                    <input pInputText type="text" [(ngModel)]="product.price" fluid />
                                </ng-template>
                                <ng-template #output>
                                    {{ product.price | currency: 'USD' }}
                                </ng-template>
                            </p-cellEditor>
                        </td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule, InputTextModule, FormsModule],
    providers: [ProductService]
})
export class TableCelleditDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }
}

checkboxselection-doc

column의 selectionMode 속성을 multiple로 활성화하면 체크박스로도 다중 선택을 처리할 수 있어요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-table [value]="products" [(selection)]="selectedProducts" dataKey="code" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th style="width: 4rem">
                            <p-tableHeaderCheckbox />
                        </th>
                        <th>Code</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Quantity</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td>
                            <p-tableCheckbox [value]="product" />
                        </td>
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [ProductService]
})
export class TableCheckboxselectionDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];
    selectedProducts!: Product;

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }
}

columngroup-doc

rowspan과 colspan 속성을 사용하면 컬럼을 그룹으로 묶을 수 있어요.

import { Component, OnInit } from '@angular/core';
import { TableModule } from 'primeng/table';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-table [value]="sales" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th rowspan="3">Product</th>
                        <th colspan="4">Sale Rate</th>
                    </tr>
                    <tr>
                        <th colspan="2">Sales</th>
                        <th colspan="2">Profits</th>
                    </tr>
                    <tr>
                        <th>Last Year</th>
                        <th>This Year</th>
                        <th>Last Year</th>
                        <th>This Year</th>
                    </tr>
                </ng-template>
                <ng-template #body let-sale>
                    <tr>
                        <td>{{ sale.product }}</td>
                        <td>{{ sale.lastYearSale }}%</td>
                        <td>{{ sale.thisYearSale }}%</td>
                        <td>{{ sale.lastYearProfit | currency: 'USD' }}</td>
                        <td>{{ sale.thisYearProfit | currency: 'USD' }}</td>
                    </tr>
                </ng-template>
                <ng-template #footer>
                    <tr>
                        <td colspan="3" class="text-right font-bold p-3 pb-0">Totals</td>
                        <td class="font-bold p-3 pb-0">{{ lastYearTotal | currency: 'USD' }}</td>
                        <td class="font-bold p-3 pb-0">{{ thisYearTotal | currency: 'USD' }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule]
})
export class TableColumngroupDemo implements OnInit {
    sales!: any[];
    lastYearTotal!: number;
    thisYearTotal!: number;

    ngOnInit() {
        this.sales = [
            {
                product: 'Bamboo Watch',
                lastYearSale: 51,
                thisYearSale: 40,
                lastYearProfit: 54406,
                thisYearProfit: 43342
            },
            {
                product: 'Black Watch',
                lastYearSale: 83,
                thisYearSale: 9,
                lastYearProfit: 423132,
                thisYearProfit: 312122
            },
            { product: 'Blue Band', lastYearSale: 38, thisYearSale: 5, lastYearProfit: 12321, thisYearProfit: 8500 },
            {
                product: 'Blue T-Shirt',
                lastYearSale: 49,
                thisYearSale: 22,
                lastYearProfit: 745232,
                thisYearProfit: 65323
            },
            {
                product: 'Brown Purse',
                lastYearSale: 17,
                thisYearSale: 79,
                lastYearProfit: 643242,
                thisYearProfit: 500332
            },
            {
                product: 'Chakra Bracelet',
                lastYearSale: 52,
                thisYearSale: 65,
                lastYearProfit: 421132,
                thisYearProfit: 150005
            },
            {
                product: 'Galaxy Earrings',
                lastYearSale: 82,
                thisYearSale: 12,
                lastYearProfit: 131211,
                thisYearProfit: 100214
            },
            {
                product: 'Game Controller',
                lastYearSale: 44,
                thisYearSale: 45,
                lastYearProfit: 66442,
                thisYearProfit: 53322
            },
            {
                product: 'Gaming Set',
                lastYearSale: 90,
                thisYearSale: 56,
                lastYearProfit: 765442,
                thisYearProfit: 296232
            },
            {
                product: 'Gold Phone Case',
                lastYearSale: 75,
                thisYearSale: 54,
                lastYearProfit: 21212,
                thisYearProfit: 12533
            }
        ];
        this.calculateLastYearTotal();
        this.calculateThisYearTotal();
    }

    calculateThisYearTotal() {
        let total = 0;
        for (let sale of this.sales) {
            total += sale.thisYearProfit;
        }
        
        this.thisYearTotal = total;
    }
}

columnresizeexpandmode-doc

columnResizeMode를 expand로 설정하면 테이블 너비도 함께 변경돼요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-table [value]="products" showGridlines [resizableColumns]="true" columnResizeMode="expand" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th pResizableColumn>Code</th>
                        <th pResizableColumn>Name</th>
                        <th pResizableColumn>Category</th>
                        <th pResizableColumn>Quantity</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [ProductService]
})
export class TableColumnresizeexpandmodeDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }
}

columnresizefitmode-doc

resizableColumns를 true로 설정하면 드래그 앤 드롭으로 컬럼 크기를 조절할 수 있어요. fit 모드가 기본값이고, 컬럼 크기를 조절해도 전체 테이블 너비는 변하지 않아요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-table [value]="products" showGridlines [resizableColumns]="true" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th pResizableColumn>Code</th>
                        <th pResizableColumn>Name</th>
                        <th pResizableColumn>Category</th>
                        <th pResizableColumn>Quantity</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [ProductService]
})
export class TableColumnresizefitmodeDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }
}

columnresizescrollablemode-doc

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { CustomerService } from '@/service/customerservice';
import { Customer, Representative, Country } from '@/domain/customer';

@Component({
    template: `
        <div class="card">
            <p-table [value]="customers" showGridlines [scrollable]="true" scrollHeight="400px" [resizableColumns]="true" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th pResizableColumn>Name</th>
                        <th pResizableColumn>Country</th>
                        <th pResizableColumn>Company</th>
                        <th pResizableColumn>Representative</th>
                    </tr>
                </ng-template>
                <ng-template #body let-customer>
                    <tr>
                        <td>{{ customer.name }}</td>
                        <td>{{ customer.country.name }}</td>
                        <td>{{ customer.company }}</td>
                        <td>{{ customer.representative.name }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [CustomerService]
})
export class TableColumnresizescrollablemodeDemo implements OnInit {
    private customerService = inject(CustomerService);
    customers!: Customer[];

    ngOnInit() {
        this.customerService.getCustomersLarge().then((customers) => {
            this.customers = customers;
        });
    }
}

columnselection-doc

컬럼 안의 엘리먼트를 활용한 행 선택은 템플릿으로 구현돼요.

import { Component, OnInit, inject } from '@angular/core';
import { ButtonModule } from 'primeng/button';
import { TableModule } from 'primeng/table';
import { ToastModule } from 'primeng/toast';
import { ProductService } from '@/service/productservice';
import { MessageService } from 'primeng/api';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-toast />
            <p-table [value]="products" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th>Code</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Quantity</th>
                        <th style="width: 5rem"></th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                        <td>
                            <p-button icon="pi pi-search" (click)="selectProduct(product)" severity="secondary" rounded />
                        </td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [ButtonModule, TableModule, ToastModule],
    providers: [ProductService, MessageService]
})
export class TableColumnselectionDemo implements OnInit {
    private productService = inject(ProductService);
    private messageService = inject(MessageService);
    products!: Product[];
    selectedProduct!: Product;

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }

    selectProduct(product: Product) {
        this.messageService.add({ severity: 'info', summary: 'Product Selected', detail: product.name });
    }
}

columntoggle-doc

이 데모에서는 multiselect 컴포넌트를 사용해서 토글할 수 있는 컬럼을 구현해요.

import { Component, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MultiSelectModule } from 'primeng/multiselect';
import { TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

interface Column {
    field: string;
    header: string;
}

@Component({
    template: `
        <div class="card">
            <p-table [columns]="selectedColumns" [value]="products" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #caption>
                    <p-multiselect display="chip" [options]="cols" [(ngModel)]="selectedColumns" optionLabel="header" selectedItemsLabel="{0} columns selected" [style]="{ 'min-width': '200px' }" placeholder="Choose Columns" />
                </ng-template>
                <ng-template #header let-columns>
                    <tr>
                        <th>Code</th>
                        <th *ngFor="let col of columns">
                            {{ col.header }}
                        </th>
                    </tr>
                </ng-template>
                <ng-template #body let-product let-columns="columns">
                    <tr>
                        <td>{{ product.code }}</td>
                        <td *ngFor="let col of columns">
                            {{ product[col.field] }}
                        </td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [MultiSelectModule, TableModule, FormsModule],
    providers: [ProductService]
})
export class TableColumntoggleDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];
    cols!: Column[];
    selectedColumns!: Column[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
        this.cols = [
            { field: 'name', header: 'Name' },
            { field: 'category', header: 'Category' },
            { field: 'quantity', header: 'Quantity' }
        ];
        this.selectedColumns = this.cols;
    }
}

contextmenu-doc

Table은 contextmenu 컴포넌트와 전용 통합을 제공해요. 테이블에 메뉴를 연결하려면, 컨텍스트 메뉴로 선택할 수 있는 행에 pContextMenuRow 디렉티브를 추가하고, 메뉴를 위한 로컬 템플릿 변수를 정의한 뒤 테이블의 contextMenu 프로퍼티에 바인딩하세요. 이렇게 하면 행을 오른쪽 클릭할 때마다 메뉴가 표시돼요. 선택 사항인 pContextMenuRowIndex 프로퍼티를 사용하면 행 인덱스에 접근할 수 있어요. 오른쪽 클릭된 행을 가져오려면 별도의 contextMenuSelection 프로퍼티가 사용돼요. 동적 컬럼의 경우, pContextMenuRowDisabled 프로퍼티를 true로 설정하면 해당 행에 대한 컨텍스트 메뉴가 비활성화돼요.

import { Component, OnInit, inject } from '@angular/core';
import { ContextMenuModule } from 'primeng/contextmenu';
import { Table, TableModule } from 'primeng/table';
import { ToastModule } from 'primeng/toast';
import { ProductService } from '@/service/productservice';
import { MenuItem, MessageService } from 'primeng/api';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-contextmenu #cm [model]="items" (onHide)="selectedProduct = null" />
            <p-table [value]="products" [(contextMenuSelection)]="selectedProduct" [contextMenu]="cm" dataKey="code" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th>Code</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Price</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr [pContextMenuRow]="product">
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.price | currency: 'USD' }}</td>
                    </tr>
                </ng-template>
            </p-table>
            <p-toast />
        </div>
    `,
    standalone: true,
    imports: [ContextMenuModule, TableModule, ToastModule],
    providers: [ProductService, MessageService]
})
export class TableContextmenuDemo implements OnInit {
    private productService = inject(ProductService);
    private messageService = inject(MessageService);
    products!: Product[];
    selectedProduct!: Product;
    items!: MenuItem[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
        this.items = [
            { label: 'View', icon: 'pi pi-fw pi-search', command: () => this.viewProduct(this.selectedProduct) },
            { label: 'Delete', icon: 'pi pi-fw pi-times', command: () => this.deleteProduct(this.selectedProduct) }
        ];
    }

    viewProduct(product: Product) {
        this.messageService.add({ severity: 'info', summary: 'Product Selected', detail: product.name });
    }

    deleteProduct(product: Product) {
        this.products = this.products.filter((p) => p.id !== product.id);
        this.messageService.add({ severity: 'error', summary: 'Product Deleted', detail: product.name });
        this.selectedProduct = null;
    }
}

고객

선택, 페이지네이션, 필터링, 정렬 그리고 템플릿 기능을 갖춘 DataTable이에요.

import { Component, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ButtonModule } from 'primeng/button';
import { SelectModule } from 'primeng/select';
import { IconFieldModule } from 'primeng/iconfield';
import { InputIconModule } from 'primeng/inputicon';
import { MultiSelectModule } from 'primeng/multiselect';
import { ProgressBarModule } from 'primeng/progressbar';
import { SliderModule } from 'primeng/slider';
import { Table, TableModule } from 'primeng/table';
import { TagModule } from 'primeng/tag';
import { InputTextModule } from 'primeng/inputtext';
import { CustomerService } from '@/service/customerservice';
import { Customer, Representative, Country } from '@/domain/customer';

@Component({
    template: `
        <div class="card">
            <p-table
                #dt
                [value]="customers"
                [(selection)]="selectedCustomers"
                dataKey="id"
                [rowHover]="true"
                [rows]="10"
                [showCurrentPageReport]="true"
                [rowsPerPageOptions]="[10, 25, 50]"
                [loading]="loading"
                [paginator]="true"
                currentPageReportTemplate="Showing {first} to {last} of {totalRecords} entries"
                [filterDelay]="0"
                [globalFilterFields]="['name', 'country.name', 'representative.name', 'status']"
            >
                <ng-template #caption>
                    <div class="flex justify-between">
                        <p-button [outlined]="true" icon="pi pi-filter-slash" label="Clear" (click)="clear(dt)" />
                        <p-iconField iconPosition="left">
                            <p-inputIcon>
                                <i class="pi pi-search"></i>
                            </p-inputIcon>
                            <input pInputText type="text" [(ngModel)]="searchValue" (input)="dt.filterGlobal($event.target.value, 'contains')" placeholder="Keyboard Search" />
                        </p-iconField>
                    </div>
                </ng-template>
                <ng-template #header>
                    <tr>
                        <th style="width: 4rem">
                            <p-tableHeaderCheckbox />
                        </th>
                        <th pSortableColumn="name" style="min-width: 14rem">
                            <div class="flex justify-between items-center gap-2">
                                Name
                                <p-sortIcon field="name" />
                                <p-columnFilter type="text" field="name" display="menu" class="ml-auto" />
                            </div>
                        </th>
                        <th pSortableColumn="country.name" style="min-width: 14rem">
                            <div class="flex justify-between items-center gap-2">
                                Country
                                <p-sortIcon field="country.name" />
                                <p-columnFilter type="text" field="country.name" display="menu" class="ml-auto" />
                            </div>
                        </th>
                        <th pSortableColumn="representative.name" style="min-width: 14rem">
                            <div class="flex justify-between items-center gap-2">
                                Agent
                                <p-sortIcon field="representative.name" />
                                <p-columnFilter field="representative" matchMode="in" display="menu" [showMatchModes]="false" [showOperator]="false" [showAddButton]="false" class="ml-auto">
                                    <ng-template #filter let-value let-filter="filterCallback">
                                        <p-multiselect [filter]="false" [(ngModel)]="value" [options]="representatives" placeholder="Any" (onChange)="filter($event.value)" optionLabel="name" class="w-full">
                                            <ng-template let-option #item>
                                                <div class="flex items-center gap-2">
                                                    <img [alt]="option.label" src="https://primefaces.org/cdn/primeng/images/demo/avatar/{{ option.image }}" style="width: 32px" />
                                                    <span>{{ option.name }}</span>
                                                </div>
                                            </ng-template>
                                        </p-multiselect>
                                    </ng-template>
                                </p-columnFilter>
                            </div>
                        </th>
                        <th pSortableColumn="date" style="min-width: 14rem">
                            <div class="flex justify-between items-center gap-2">
                                Date
                                <p-sortIcon field="date" />
                                <p-columnFilter type="date" field="date" display="menu" class="ml-auto" />
                            </div>
                        </th>
                        <th pSortableColumn="balance" style="min-width: 14rem">
                            <div class="flex justify-between items-center gap-2">
                                Balance
                                <p-sortIcon field="balance" />
                                <p-columnFilter type="numeric" field="balance" display="menu" currency="USD" class="ml-auto" />
                            </div>
                        </th>
                        <th pSortableColumn="status" style="min-width: 14rem">
                            <div class="flex justify-between items-center gap-2">
                                Status
                                <p-sortIcon field="status" />
                                <p-columnFilter field="status" matchMode="equals" display="menu" class="ml-auto">
                                    <ng-template #filter let-value let-filter="filterCallback">
                                        <p-select [(ngModel)]="value" [options]="statuses" (onChange)="filter($event.value)" placeholder="Any">
                                            <ng-template let-option #item>
                                                <p-tag [value]="option.label" [severity]="getSeverity(option.label)" />
                                            </ng-template>
                                        </p-select>
                                    </ng-template>
                                </p-columnFilter>
                            </div>
                        </th>
                        <th pSortableColumn="activity" style="min-width: 14rem">
                            <div class="flex justify-between items-center gap-2">
                                Activity
                                <p-sortIcon field="activity" />
                                <p-columnFilter field="activity" matchMode="between" display="menu" [showMatchModes]="false" [showOperator]="false" [showAddButton]="false" class="ml-auto">
                                    <ng-template #filter let-filter="filterCallback">
                                        <p-slider [(ngModel)]="activityValues" [range]="true" (onSlideEnd)="filter($event.values)" class="m-4"></p-slider>
                                        <div class="flex items-center justify-between px-2">
                                            <span>{{ activityValues[0] }}</span>
                                            <span>{{ activityValues[1] }}</span>
                                        </div>
                                    </ng-template>
                                </p-columnFilter>
                            </div>
                        </th>
                        <th style="width: 5rem"></th>
                    </tr>
                </ng-template>
                <ng-template #body let-customer>
                    <tr class="p-selectable-row">
                        <td>
                            <p-tableCheckbox [value]="customer" />
                        </td>
                        <td>
                            {{ customer.name }}
                        </td>
                        <td>
                            <div class="flex items-center gap-2">
                                <img src="https://primefaces.org/cdn/primeng/images/demo/flag/flag_placeholder.png" [class]="'flag flag-' + customer.country.code" style="width: 20px" />
                                <span class="ml-1 align-middle">{{ customer.country.name }}</span>
                            </div>
                        </td>
                        <td>
                            <div class="flex items-center gap-2">
                                <img [alt]="customer.representative.name" src="https://primefaces.org/cdn/primeng/images/demo/avatar/{{ customer.representative.image }}" width="32" style="vertical-align: middle" />
                                <span class="ml-1 align-middle">{{ customer.representative.name }}</span>
                            </div>
                        </td>
                        <td>
                            {{ customer.date | date: 'MM/dd/yyyy' }}
                        </td>
                        <td>
                            {{ customer.balance | currency: 'USD' : 'symbol' }}
                        </td>
                        <td>
                            <p-tag [value]="customer.status" [severity]="getSeverity(customer.status)" />
                        </td>
                        <td>
                            <p-progressBar [value]="customer.activity" [showValue]="false" />
                        </td>
                        <td style="text-align: center">
                            <p-button rounded icon="pi pi-cog" />
                        </td>
                    </tr>
                </ng-template>
                <ng-template #emptymessage>
                    <tr>
                        <td colspan="8">No customers found.</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [ButtonModule, SelectModule, IconFieldModule, InputIconModule, MultiSelectModule, ProgressBarModule, SliderModule, TableModule, TagModule, InputTextModule, FormsModule],
    providers: [CustomerService]
})
export class TableCustomersDemo implements OnInit {
    private customerService = inject(CustomerService);
    customers!: Customer[];
    selectedCustomers!: Customer[];
    representatives!: Representative[];
    statuses!: any[];
    loading: boolean = true;
    activityValues: number[] = [0, 100];
    searchValue: string | undefined;

    ngOnInit() {
        this.customerService.getCustomersLarge().then((customers) => {
            this.customers = customers;
            this.loading = false;
            this.customers.forEach((customer) => (customer.date = new Date(<Date>customer.date)));
        });
        this.representatives = [
            { name: 'Amy Elsner', image: 'amyelsner.png' },
            { name: 'Anna Fali', image: 'annafali.png' },
            { name: 'Asiya Javayant', image: 'asiyajavayant.png' },
            { name: 'Bernardo Dominic', image: 'bernardodominic.png' },
            { name: 'Elwin Sharvill', image: 'elwinsharvill.png' },
            { name: 'Ioni Bowcher', image: 'ionibowcher.png' },
            { name: 'Ivan Magalhaes', image: 'ivanmagalhaes.png' },
            { name: 'Onyama Limba', image: 'onyamalimba.png' },
            { name: 'Stephen Shaw', image: 'stephenshaw.png' },
            { name: 'Xuxue Feng', image: 'xuxuefeng.png' }
        ];
        this.statuses = [
            { label: 'Unqualified', value: 'unqualified' },
            { label: 'Qualified', value: 'qualified' },
            { label: 'New', value: 'new' },
            { label: 'Negotiation', value: 'negotiation' },
            { label: 'Renewal', value: 'renewal' },
            { label: 'Proposal', value: 'proposal' }
        ];
    }

    clear(dt: Table) {
        this.searchValue = '';
        dt.reset();
    }

    getSeverity(status: string) {
        switch (status) {
            case 'unqualified':
                return 'danger';
        
            case 'qualified':
                return 'success';
        
            case 'new':
                return 'info';
        
            case 'negotiation':
                return 'warn';
        
            case 'renewal':
                return null;
        }
    }
}

동적 컬럼

*ngFor 디렉티브를 사용하면 컬럼을 동적으로 정의할 수 있어요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

interface Column {
    field: string;
    header: string;
}

@Component({
    template: `
        <div class="card">
            <p-table [columns]="cols" [value]="products" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header let-columns>
                    <tr>
                        @for (col of columns; track col) {
                            <th>
                                {{ col.header }}
                            </th>
                        }
                    </tr>
                </ng-template>
                <ng-template #body let-rowData let-columns="columns">
                    <tr>
                        @for (col of columns; track col) {
                            <td>
                                {{ rowData[col.field] }}
                            </td>
                        }
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [ProductService]
})
export class TableDynamicDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];
    cols!: Column[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
        this.cols = [
            { field: 'code', header: 'Code' },
            { field: 'name', header: 'Name' },
            { field: 'category', header: 'Category' },
            { field: 'quantity', header: 'Quantity' }
        ];
    }
}

expandablerowgroup-doc

서브헤더 기반 행 그룹핑에서 expandableRowGroups가 있으면 그룹을 펼치거나 접을 수 있어요. 펼침 상태는 expandedRows와 onRowToggle 프로퍼티로 제어해요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { TagModule } from 'primeng/tag';
import { ButtonModule } from 'primeng/button';
import { RippleModule } from 'primeng/ripple';
import { CustomerService } from '@/service/customerservice';
import { Customer, Country } from '@/domain/customer';

@Component({
    template: `
        <div class="card">
            <p-table [value]="customers" sortField="representative.name" sortMode="single" dataKey="representative.name" rowGroupMode="subheader" groupRowsBy="representative.name" [tableStyle]="{ 'min-width': '70rem' }">
                <ng-template #header>
                    <tr>
                        <th style="width:20%">Name</th>
                        <th style="width:20%">Country</th>
                        <th style="width:20%">Company</th>
                        <th style="width:20%">Status</th>
                        <th style="width:20%">Date</th>
                    </tr>
                </ng-template>
                <ng-template #groupheader let-customer let-rowIndex="rowIndex" let-expanded="expanded">
                    <tr>
                        <td colspan="5">
                            <button type="button" pButton pRipple [pRowToggler]="customer" text rounded plain class="mr-2" [icon]="expanded ? 'pi pi-chevron-down' : 'pi pi-chevron-right'"></button>
                            <img [alt]="customer.representative.name" src="https://primefaces.org/cdn/primeng/images/demo/avatar/{{ customer.representative.image }}" width="32" style="vertical-align: middle; display: inline-block" />
                            <span class="font-bold ml-2">{{ customer.representative.name }}</span>
                        </td>
                    </tr>
                </ng-template>
                <ng-template #groupfooter let-customer>
                    <tr class="p-rowgroup-footer">
                        <td colspan="4" style="text-align: right">Total Customers</td>
                        <td>{{ calculateCustomerTotal(customer.representative.name) }}</td>
                    </tr>
                </ng-template>
                <ng-template #expandedrow let-customer>
                    <tr>
                        <td>
                            {{ customer.name }}
                        </td>
                        <td>
                            <div class="flex items-center gap-2">
                                <img src="https://primefaces.org/cdn/primeng/images/demo/flag/flag_placeholder.png" [class]="'flag flag-' + customer.country.code" style="width: 20px" />
                                <span>{{ customer.country.name }}</span>
                            </div>
                        </td>
                        <td>
                            {{ customer.company }}
                        </td>
                        <td>
                            <p-tag [value]="customer.status" [severity]="getSeverity(customer.status)" />
                        </td>
                        <td>
                            {{ customer.date }}
                        </td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule, TagModule, ButtonModule, RippleModule],
    providers: [CustomerService]
})
export class TableExpandablerowgroupDemo implements OnInit {
    private customerService = inject(CustomerService);
    customers!: Customer[];

    ngOnInit() {
        this.customerService.getCustomersMedium().then((data) => {
            this.customers = data;
        });
    }

    calculateCustomerTotal(name: string) {
        let total = 0;
        
        if (this.customers) {
            for (let customer of this.customers) {
                if (customer.representative?.name === name) {
                    total++;
                }
            }
        }
        
        return total;
    }

    getSeverity(status: string) {
        switch (status) {
            case 'unqualified':
                return 'danger';
        
            case 'qualified':
                return 'success';
        
            case 'new':
                return 'info';
        
            case 'negotiation':
                return 'warn';
        
            case 'renewal':
                return null;
        }
    }
}

내보내기

테이블은 데이터를 CSV 형식으로 내보낼 수 있어요.

import { Component, OnInit, inject } from '@angular/core';
import { ButtonModule } from 'primeng/button';
import { TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

interface Column {
    field: string;
    header: string;
    customExportHeader?: string;
}

interface ExportColumn {
    title: string;
    dataKey: string;
}

@Component({
    template: `
        <div class="card">
            <p-table #dt [columns]="cols" [value]="products" [exportHeader]="'customExportHeader'" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #caption>
                    <div class="text-end pb-4">
                        <p-button icon="pi pi-external-link" label="Export" (click)="dt.exportCSV()" />
                    </div>
                </ng-template>
                <ng-template #header let-columns>
                    <tr>
                        <th *ngFor="let col of columns">
                            {{ col.header }}
                        </th>
                    </tr>
                </ng-template>
                <ng-template #body let-rowData let-columns="columns">
                    <tr>
                        <td *ngFor="let col of columns">
                            {{ rowData[col.field] }}
                        </td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [ButtonModule, TableModule],
    providers: [ProductService]
})
export class TableExportDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];
    selectedProducts!: Product[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
        this.cols = [
            { field: 'code', header: 'Code', customExportHeader: 'Product Code' },
            { field: 'name', header: 'Name' },
            { field: 'category', header: 'Category' },
            { field: 'quantity', header: 'Quantity' }
        ];
        this.exportColumns = this.cols.map((col) => ({ title: col.header, dataKey: col.field }));
    }
}

고급

필터는 오버레이로 표시돼요.

import { Component, OnInit, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ButtonModule } from 'primeng/button';
import { SelectModule } from 'primeng/select';
import { IconFieldModule } from 'primeng/iconfield';
import { InputIconModule } from 'primeng/inputicon';
import { MultiSelectModule } from 'primeng/multiselect';
import { ProgressBarModule } from 'primeng/progressbar';
import { SliderModule } from 'primeng/slider';
import { Table, TableModule } from 'primeng/table';
import { TagModule } from 'primeng/tag';
import { InputTextModule } from 'primeng/inputtext';
import { CustomerService } from '@/service/customerservice';
import { Customer, Representative, Country } from '@/domain/customer';

@Component({
    template: `
        <div class="card">
            <p-table #dt1 [value]="customers()" dataKey="id" [rows]="10" [rowsPerPageOptions]="[10, 25, 50]" [loading]="loading()" [paginator]="true" [globalFilterFields]="['name', 'country.name', 'representative.name', 'status']" showGridlines>
                <ng-template #caption>
                    <div class="flex">
                        <p-button label="Clear" [outlined]="true" icon="pi pi-filter-slash" (click)="clear(dt1)" />
                        <p-iconfield iconPosition="left" class="ml-auto">
                            <p-inputicon>
                                <i class="pi pi-search"></i>
                            </p-inputicon>
                            <input pInputText type="text" (input)="dt1.filterGlobal($event.target.value, 'contains')" placeholder="Search keyword" />
                        </p-iconfield>
                    </div>
                </ng-template>
                <ng-template #header>
                    <tr>
                        <th style="min-width:15rem">
                            <div class="flex items-center justify-between">
                                Name
                                <p-columnFilter type="text" field="name" display="menu" />
                            </div>
                        </th>
                        <th style="min-width:15rem">
                            <div class="flex items-center justify-between">
                                Country
                                <p-columnFilter type="text" field="country.name" display="menu" />
                            </div>
                        </th>
                        <th style="min-width:15rem">
                            <div class="flex items-center justify-between">
                                Agent
                                <p-columnFilter field="representative" matchMode="in" display="menu" [showMatchModes]="false" [showOperator]="false" [showAddButton]="false">
                                    <ng-template #filter let-value let-filter="filterCallback">
                                        <p-multiselect [(ngModel)]="value" [options]="representatives()" placeholder="Any" (onChange)="filter($event.value)" optionLabel="name" style="min-width: 14rem" [panelStyle]="{ minWidth: '16rem' }">
                                            <ng-template let-option #item>
                                                <div class="flex items-center gap-2">
                                                    <img [alt]="option.label" src="https://primefaces.org/cdn/primeng/images/demo/avatar/{{ option.image }}" style="width: 32px" />
                                                    <span>{{ option.name }}</span>
                                                </div>
                                            </ng-template>
                                        </p-multiselect>
                                    </ng-template>
                                </p-columnFilter>
                            </div>
                        </th>
                        <th style="min-width:10rem">
                            <div class="flex items-center justify-between">
                                Date
                                <p-columnFilter type="date" field="date" display="menu"></p-columnFilter>
                            </div>
                        </th>
                        <th style="min-width:10rem">
                            <div class="flex items-center justify-between">
                                Balance
                                <p-columnFilter type="numeric" field="balance" display="menu" currency="USD" />
                            </div>
                        </th>
                        <th style="min-width:10rem">
                            <div class="flex items-center justify-between">
                                Status
                                <p-columnFilter field="status" matchMode="equals" display="menu">
                                    <ng-template #filter let-value let-filter="filterCallback">
                                        <p-select [(ngModel)]="value" [options]="statuses()" (onChange)="filter($event.value)" placeholder="Select One" class="w-full">
                                            <ng-template let-option #item>
                                                <p-tag [value]="option.value" [severity]="getSeverity(option.value)"></p-tag>
                                            </ng-template>
                                        </p-select>
                                    </ng-template>
                                </p-columnFilter>
                            </div>
                        </th>
                        <th style="min-width:10rem">
                            <div class="flex items-center justify-between">
                                Activity
                                <p-columnFilter field="activity" matchMode="between" display="menu" [showMatchModes]="false" [showOperator]="false" [showAddButton]="false">
                                    <ng-template #filter let-value let-filter="filterCallback">
                                        <p-slider [(ngModel)]="value" [range]="true" class="m-4" (onSlideEnd)="filter($event.values)" />
                                        <div class="flex items-center px-2">
                                            <span *ngIf="!value">0</span>
                                            <span *ngIf="value">{{ value[0] }} - {{ value[1] }}</span>
                                        </div>
                                    </ng-template>
                                </p-columnFilter>
                            </div>
                        </th>
                        <th style="width: 3rem">
                            <div class="flex items-center justify-between">
                                Verified
                                <p-columnFilter type="boolean" field="verified" display="menu" />
                            </div>
                        </th>
                    </tr>
                </ng-template>
                <ng-template #body let-customer>
                    <tr>
                        <td>
                            {{ customer.name }}
                        </td>
                        <td>
                            <div class="flex items-center gap-2">
                                <img src="https://primefaces.org/cdn/primeng/images/demo/flag/flag_placeholder.png" [class]="'flag flag-' + customer.country.code" style="width: 20px" />
                                <span>{{ customer.country.name }}</span>
                            </div>
                        </td>
                        <td>
                            <div class="flex items-center gap-2">
                                <img [alt]="customer.representative.name" src="https://primefaces.org/cdn/primeng/images/demo/avatar/{{ customer.representative.image }}" width="32" />
                                <span>{{ customer.representative.name }}</span>
                            </div>
                        </td>
                        <td>
                            {{ customer.date | date: 'MM/dd/yyyy' }}
                        </td>
                        <td>
                            {{ customer.balance | currency: 'USD' : 'symbol' }}
                        </td>
                        <td>
                            <p-tag [value]="customer.status" [severity]="getSeverity(customer.status)" />
                        </td>
                        <td>
                            <p-progressbar [value]="customer.activity" [showValue]="false" />
                        </td>
                        <td class="text-center">
                            <i
                                class="pi"
                                [ngClass]="{
                                    'text-green-500 pi-check-circle': customer.verified,
                                    'text-red-500 pi-times-circle': !customer.verified
                                }"
                            ></i>
                        </td>
                    </tr>
                </ng-template>
                <ng-template #emptymessage>
                    <tr>
                        <td colspan="7">No customers found.</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [ButtonModule, SelectModule, IconFieldModule, InputIconModule, MultiSelectModule, ProgressBarModule, SliderModule, TableModule, TagModule, InputTextModule, FormsModule],
    providers: [CustomerService]
})
export class TableFilterAdvancedDemo implements OnInit {
    private customerService = inject(CustomerService);
    customerService = inject(CustomerService);
    customers = signal<Customer[]>([]);
    representatives = signal<Representative[]>([]);
    statuses = signal<any[]>([]);
    loading = signal(true);
    searchValue = signal('');
    activityValues = signal<number[]>([0, 100]);

    ngOnInit() {
        this.customerService.getCustomersLarge().then((customers) => {
            customers.forEach((customer: Customer) => (customer.date = new Date(customer.date as string)));
            this.customers.set(customers);
            this.loading.set(false);
        });
        this.representatives.set([
            { name: 'Amy Elsner', image: 'amyelsner.png' },
            { name: 'Anna Fali', image: 'annafali.png' },
            { name: 'Asiya Javayant', image: 'asiyajavayant.png' },
            { name: 'Bernardo Dominic', image: 'bernardodominic.png' },
            { name: 'Elwin Sharvill', image: 'elwinsharvill.png' },
            { name: 'Ioni Bowcher', image: 'ionibowcher.png' },
            { name: 'Ivan Magalhaes', image: 'ivanmagalhaes.png' },
            { name: 'Onyama Limba', image: 'onyamalimba.png' },
            { name: 'Stephen Shaw', image: 'stephenshaw.png' },
            { name: 'Xuxue Feng', image: 'xuxuefeng.png' }
        ]);
        this.statuses.set([
            { label: 'Unqualified', value: 'unqualified' },
            { label: 'Qualified', value: 'qualified' },
            { label: 'New', value: 'new' },
            { label: 'Negotiation', value: 'negotiation' },
            { label: 'Renewal', value: 'renewal' },
            { label: 'Proposal', value: 'proposal' }
        ]);
    }

    clear(table: Table) {
        table.clear();
        this.searchValue.set('');
    }

    getSeverity(status: string) {
        switch (status) {
            case 'unqualified':
                return 'danger';
        
            case 'qualified':
                return 'success';
        
            case 'new':
                return 'info';
        
            case 'negotiation':
                return 'warn';
        
            case 'renewal':
                return null;
        }
    }
}

filterbasic-doc

filters 프로퍼티를 DataTableFilterMeta 인스턴스를 참조하도록 정의하면 데이터 필터링이 활성화돼요. 필터링하려는 각 컬럼에도 filter가 활성화되어 있어야 해요. 기본 제공 필터 엘리먼트는 입력 필드이고, filterElement를 사용하면 자신만의 UI로 필터링을 커스터마이즈할 수 있어요. 선택 사항인 전역 필터링은 filters 객체의 global 키에 바인딩된 단일 값으로 데이터를 검색해요. 검색 대상이 되는 필드는 globalFilterFields로 정의해요.

import { Component, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { SelectModule } from 'primeng/select';
import { IconFieldModule } from 'primeng/iconfield';
import { InputIconModule } from 'primeng/inputicon';
import { MultiSelectModule } from 'primeng/multiselect';
import { Table, TableModule } from 'primeng/table';
import { TagModule } from 'primeng/tag';
import { InputTextModule } from 'primeng/inputtext';
import { CustomerService } from '@/service/customerservice';
import { Customer, Representative, Country } from '@/domain/customer';

@Component({
    template: `
        <div class="card">
            <p-table
                #dt2
                [value]="customers"
                dataKey="id"
                [rows]="10"
                [rowsPerPageOptions]="[10, 25, 50]"
                [loading]="loading"
                [paginator]="true"
                [globalFilterFields]="['name', 'country.name', 'representative.name', 'status']"
                [tableStyle]="{ 'min-width': '75rem' }"
            >
                <ng-template #caption>
                    <div class="flex">
                        <p-iconfield iconPosition="left" class="ml-auto">
                            <p-inputicon>
                                <i class="pi pi-search"></i>
                            </p-inputicon>
                            <input pInputText type="text" (input)="dt2.filterGlobal($event.target.value, 'contains')" placeholder="Search keyword" />
                        </p-iconfield>
                    </div>
                </ng-template>
                <ng-template #header>
                    <tr>
                        <th style="width:22%">Name</th>
                        <th style="width:22%">Country</th>
                        <th style="width:22%">Agent</th>
                        <th style="width:22%">Status</th>
                        <th style="width:12%">Verified</th>
                    </tr>
                    <tr>
                        <th>
                            <p-columnFilter type="text" field="name" placeholder="Type to search" ariaLabel="Filter Name" filterOn="input"></p-columnFilter>
                        </th>
                        <th>
                            <p-columnFilter type="text" field="country.name" placeholder="Enter key to search" ariaLabel="Filter Country"></p-columnFilter>
                        </th>
                        <th>
                            <p-columnFilter field="representative" matchMode="in" [showMenu]="false">
                                <ng-template #filter let-value let-filter="filterCallback">
                                    <p-multiselect [(ngModel)]="value" [options]="representatives" placeholder="Any" (onChange)="filter($event.value)" optionLabel="name" style="min-width: 14rem" [panelStyle]="{ minWidth: '16rem' }">
                                        <ng-template let-option #item>
                                            <div class="flex items-center gap-2">
                                                <img [alt]="option.label" src="https://primefaces.org/cdn/primeng/images/demo/avatar/{{ option.image }}" style="width: 32px" />
                                                <span>{{ option.name }}</span>
                                            </div>
                                        </ng-template>
                                    </p-multiselect>
                                </ng-template>
                            </p-columnFilter>
                        </th>
                        <th>
                            <p-columnFilter field="status" matchMode="equals" [showMenu]="false">
                                <ng-template #filter let-value let-filter="filterCallback">
                                    <p-select [(ngModel)]="value" [options]="statuses" (onChange)="filter($event.value)" placeholder="Select One" [showClear]="true" style="min-width: 12rem">
                                        <ng-template let-option #item>
                                            <p-tag [value]="option.value" [severity]="getSeverity(option.value)" />
                                        </ng-template>
                                    </p-select>
                                </ng-template>
                            </p-columnFilter>
                        </th>
                        <th>
                            <p-columnFilter type="boolean" field="verified"></p-columnFilter>
                        </th>
                    </tr>
                </ng-template>
                <ng-template #body let-customer>
                    <tr>
                        <td>
                            {{ customer.name }}
                        </td>
                        <td>
                            <div class="flex items-center gap-2">
                                <img src="https://primefaces.org/cdn/primeng/images/demo/flag/flag_placeholder.png" [class]="'flag flag-' + customer.country.code" style="width: 20px" />
                                <span>{{ customer.country.name }}</span>
                            </div>
                        </td>
                        <td>
                            <div class="flex items-center gap-2">
                                <img [alt]="customer.representative.name" src="https://primefaces.org/cdn/primeng/images/demo/avatar/{{ customer.representative.image }}" width="32" style="vertical-align: middle" />
                                <span>{{ customer.representative.name }}</span>
                            </div>
                        </td>
                        <td>
                            <p-tag [value]="customer.status" [severity]="getSeverity(customer.status)" />
                        </td>
                        <td>
                            <i
                                class="pi"
                                [ngClass]="{
                                    'text-green-500 pi-check-circle': customer.verified,
                                    'text-red-500 pi-times-circle': !customer.verified
                                }"
                            ></i>
                        </td>
                    </tr>
                </ng-template>
                <ng-template #emptymessage>
                    <tr>
                        <td colspan="5">No customers found.</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [SelectModule, IconFieldModule, InputIconModule, MultiSelectModule, TableModule, TagModule, InputTextModule, FormsModule],
    providers: [CustomerService]
})
export class TableFilterbasicDemo implements OnInit {
    private customerService = inject(CustomerService);
    customers!: Customer[];
    representatives!: Representative[];
    statuses!: any[];
    loading: boolean = true;
    activityValues: number[] = [0, 100];

    ngOnInit() {
        this.customerService.getCustomersLarge().then((customers) => {
            this.customers = customers;
            this.loading = false;
            this.customers.forEach((customer) => (customer.date = new Date(<Date>customer.date)));
        });
        this.representatives = [
            { name: 'Amy Elsner', image: 'amyelsner.png' },
            { name: 'Anna Fali', image: 'annafali.png' },
            { name: 'Asiya Javayant', image: 'asiyajavayant.png' },
            { name: 'Bernardo Dominic', image: 'bernardodominic.png' },
            { name: 'Elwin Sharvill', image: 'elwinsharvill.png' },
            { name: 'Ioni Bowcher', image: 'ionibowcher.png' },
            { name: 'Ivan Magalhaes', image: 'ivanmagalhaes.png' },
            { name: 'Onyama Limba', image: 'onyamalimba.png' },
            { name: 'Stephen Shaw', image: 'stephenshaw.png' },
            { name: 'Xuxue Feng', image: 'xuxuefeng.png' }
        ];
        this.statuses = [
            { label: 'Unqualified', value: 'unqualified' },
            { label: 'Qualified', value: 'qualified' },
            { label: 'New', value: 'new' },
            { label: 'Negotiation', value: 'negotiation' },
            { label: 'Renewal', value: 'renewal' },
            { label: 'Proposal', value: 'proposal' }
        ];
    }

    clear(table: Table) {
        table.clear();
    }

    getSeverity(status: string) {
        switch (status) {
            case 'unqualified':
                return 'danger';
        
            case 'qualified':
                return 'success';
        
            case 'new':
                return 'info';
        
            case 'negotiation':
                return 'warn';
        
            case 'renewal':
                return null;
        }
    }
}

flexiblescroll-doc

플렉스 스크롤 기능은 스크롤 가능한 뷰포트 섹션을 고정 값 대신 동적으로 만들어서, 테이블의 부모 크기에 맞춰 늘어나거나 줄어들 수 있게 해줘요. 아래 버튼을 클릭하면 크기 변화에 따라 데이터 뷰포트가 스스로 조정되는 최대화 가능한 Dialog가 표시돼요.

import { Component, OnInit, inject } from '@angular/core';
import { ButtonModule } from 'primeng/button';
import { Dialog, DialogModule } from 'primeng/dialog';
import { TableModule } from 'primeng/table';
import { CustomerService } from '@/service/customerservice';
import { Customer, Representative, Country } from '@/domain/customer';

@Component({
    template: `
        <div class="card">
            <div class="flex justify-center">
                <button type="button" (click)="showDialog()" pButton icon="pi pi-external-link" label="Show"></button>
            </div>
            <p-dialog header="Header" [resizable]="false" [modal]="true" [maximizable]="true" appendTo="body" [(visible)]="dialogVisible" [style]="{ width: '75vw' }" [contentStyle]="{ height: '300px' }">
                <p-table [value]="customers" [scrollable]="true" scrollHeight="flex" [tableStyle]="{ 'min-width': '50rem' }">
                    <ng-template #header>
                        <tr>
                            <th>Name</th>
                            <th>Country</th>
                            <th>Company</th>
                            <th>Representative</th>
                        </tr>
                    </ng-template>
                    <ng-template #body let-customer>
                        <tr>
                            <td>{{ customer.name }}</td>
                            <td>{{ customer.country.name }}</td>
                            <td>{{ customer.company }}</td>
                            <td>{{ customer.representative.name }}</td>
                        </tr>
                    </ng-template>
                </p-table>
                <ng-template #footer>
                    <p-button label="Ok" icon="pi pi-check" (onClick)="dialogVisible = false" />
                </ng-template>
            </p-dialog>
        </div>
    `,
    standalone: true,
    imports: [ButtonModule, DialogModule, TableModule],
    providers: [CustomerService]
})
export class TableFlexiblescrollDemo implements OnInit {
    private customerService = inject(CustomerService);
    customers!: Customer[];
    dialogVisible: boolean = false;

    ngOnInit() {
        this.customerService.getCustomersMedium().then((data) => {
            this.customers = data;
        });
    }

    showDialog() {
        this.dialogVisible = true;
    }
}

frozencolumns-doc

테이블 컴포넌트의 pFrozenColumn 디렉티브를 사용하면 특정 컬럼을 고정할 수 있어요. 또한 alignFrozen을 사용하면 컬럼을 왼쪽에 고정할지 오른쪽에 고정할지 정의할 수 있어요.

import { Component, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { TableModule } from 'primeng/table';
import { ToggleButtonModule } from 'primeng/togglebutton';
import { CustomerService } from '@/service/customerservice';
import { Customer, Representative, Country } from '@/domain/customer';

@Component({
    template: `
        <div class="card">
            <p-togglebutton [(ngModel)]="balanceFrozen" [onIcon]="'pi pi-lock'" offIcon="pi pi-lock-open" [onLabel]="'Balance'" offLabel="Balance" />
            <p-table [value]="customers" [scrollable]="true" scrollHeight="400px" class="mt-4">
                <ng-template #header>
                    <tr>
                        <th style="min-width:200px" pFrozenColumn class="font-bold">Name</th>
                        <th style="min-width:100px">Id</th>
                        <th style="min-width:200px">Country</th>
                        <th style="min-width:200px">Date</th>
                        <th style="min-width:200px">Company</th>
                        <th style="min-width:200px">Status</th>
                        <th style="min-width:200px">Activity</th>
                        <th style="min-width:200px">Representative</th>
                        <th style="min-width:200px" alignFrozen="right" pFrozenColumn [frozen]="balanceFrozen" [ngClass]="{ 'font-bold': balanceFrozen }">Balance</th>
                    </tr>
                </ng-template>
                <ng-template #body let-customer>
                    <tr>
                        <td pFrozenColumn class="font-bold">{{ customer.name }}</td>
                        <td style="min-width:100px">{{ customer.id }}</td>
                        <td>{{ customer.country.name }}</td>
                        <td>{{ customer.date }}</td>
                        <td>{{ customer.company }}</td>
                        <td>{{ customer.status }}</td>
                        <td>{{ customer.activity }}</td>
                        <td>{{ customer.representative.name }}</td>
                        <td alignFrozen="right" pFrozenColumn [frozen]="balanceFrozen" [ngClass]="{ 'font-bold': balanceFrozen }">
                            {{ formatCurrency(customer.balance) }}
                        </td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule, ToggleButtonModule, FormsModule],
    providers: [CustomerService]
})
export class TableFrozencolumnsDemo implements OnInit {
    private customerService = inject(CustomerService);
    balanceFrozen: boolean = false;
    customers!: Customer[];

    ngOnInit() {
        this.customerService.getCustomersMedium().then((data) => {
            this.customers = data;
        });
    }

    formatCurrency(value: number) {
        return value.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
    }
}

frozenrows-doc

고정 행은 스크롤하는 동안 특정 행을 고정할 때 사용해요. 이 데이터는 frozenValue 프로퍼티로 정의해요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { ButtonModule } from 'primeng/button';
import { RippleModule } from 'primeng/ripple';
import { CustomerService } from '@/service/customerservice';
import { Customer, Representative, Country } from '@/domain/customer';

@Component({
    template: `
        <div class="card">
            <p-table [value]="unlockedCustomers" [frozenValue]="lockedCustomers" [scrollable]="true" scrollHeight="400px" [tableStyle]="{ 'min-width': '60rem' }">
                <ng-template #header>
                    <tr>
                        <th>Name</th>
                        <th>Country</th>
                        <th>Company</th>
                        <th>Representative</th>
                        <th style="width:5rem"></th>
                    </tr>
                </ng-template>
                <ng-template #frozenbody let-customer let-index="rowIndex">
                    <tr class="font-bold">
                        <td>{{ customer.name }}</td>
                        <td>{{ customer.country.name }}</td>
                        <td>{{ customer.company }}</td>
                        <td>{{ customer.representative.name }}</td>
                        <td>
                            <button pButton pRipple type="button" [icon]="'pi pi-lock-open'" (click)="toggleLock(customer, true, index)" size="small" text></button>
                        </td>
                    </tr>
                </ng-template>
                <ng-template #body let-customer let-index="rowIndex">
                    <tr>
                        <td>{{ customer.name }}</td>
                        <td>{{ customer.country.name }}</td>
                        <td>{{ customer.company }}</td>
                        <td>{{ customer.representative.name }}</td>
                        <td>
                            <button pButton pRipple type="button" [icon]="'pi pi-lock'" [disabled]="lockedCustomers.length >= 2" (click)="toggleLock(customer, false, index)" size="small" text></button>
                        </td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule, ButtonModule, RippleModule],
    providers: [CustomerService]
})
export class TableFrozenrowsDemo implements OnInit {
    private customerService = inject(CustomerService);
    unlockedCustomers!: Customer[];
    lockedCustomers!: Customer[];

    ngOnInit() {
        this.customerService.getCustomersMedium().then((data) => {
            this.unlockedCustomers = data;
        });
        this.lockedCustomers = [
            {
                id: 5135,
                name: 'Geraldine Bisset',
                country: {
                    name: 'France',
                    code: 'fr'
                },
                company: 'Bisset Group',
                status: 'proposal',
                date: '2019-05-05',
                activity: 0,
                representative: {
                    name: 'Amy Elsner',
                    image: 'amyelsner.png'
                }
            }
        ];
    }

    toggleLock(data: Customer, frozen: boolean, index: number) {
        if (frozen) {
            this.lockedCustomers = this.lockedCustomers.filter((c, i) => i !== index);
            this.unlockedCustomers.push(data);
        } else {
            this.unlockedCustomers = this.unlockedCustomers.filter((c, i) => i !== index);
            this.lockedCustomers.push(data);
        }
        
        this.unlockedCustomers.sort((val1, val2) => {
            return val1.id < val2.id ? -1 : 1;
        });
    }
}

그리드 라인

showGridlines를 활성화하면 셀 사이에 테두리가 표시돼요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-table [value]="products" showGridlines [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th>Code</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Quantity</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [ProductService]
})
export class TableGridlinesDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }
}

horizontalscroll-doc

테이블 너비가 부모 너비를 초과하면 가로 스크롤바가 표시돼요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { CustomerService } from '@/service/customerservice';
import { Customer, Representative, Country } from '@/domain/customer';

@Component({
    template: `
        <div class="card">
            <p-table [value]="customers" [scrollable]="true" scrollHeight="400px">
                <ng-template #header>
                    <tr>
                        <th style="min-width:100px">Id</th>
                        <th style="min-width:200px">Name</th>
                        <th style="min-width:200px">Country</th>
                        <th style="min-width:200px">Date</th>
                        <th style="min-width:200px">Balance</th>
                        <th style="min-width:200px">Company</th>
                        <th style="min-width:200px">Status</th>
                        <th style="min-width:200px">Activity</th>
                        <th style="min-width:200px">Representative</th>
                    </tr>
                </ng-template>
                <ng-template #body let-customer>
                    <tr>
                        <td>{{ customer.id }}</td>
                        <td>{{ customer.name }}</td>
                        <td>{{ customer.country.name }}</td>
                        <td>{{ customer.date }}</td>
                        <td>{{ formatCurrency(customer.balance) }}</td>
                        <td>{{ customer.company }}</td>
                        <td>{{ customer.status }}</td>
                        <td>{{ customer.activity }}</td>
                        <td>{{ customer.representative.name }}</td>
                    </tr>
                </ng-template>
                <ng-template #footer>
                    <tr class="font-bold">
                        <td>Id</td>
                        <td>Name</td>
                        <td>Country</td>
                        <td>Date</td>
                        <td>Balance</td>
                        <td>Company</td>
                        <td>Status</td>
                        <td>Activity</td>
                        <td>Representative</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [CustomerService]
})
export class TableHorizontalscrollDemo implements OnInit {
    private customerService = inject(CustomerService);
    customers!: Customer[];

    ngOnInit() {
        this.customerService.getCustomersMedium().then((data) => {
            this.customers = data;
        });
    }

    formatCurrency(value: number) {
        return value.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
    }
}

loadingmask-doc

loading 속성은 바쁜 상태를 나타내기 위해 마스크 레이어를 표시해요. 마스크를 표시하려면 paginator를 사용하세요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-table [value]="products" [tableStyle]="{ 'min-width': '50rem' }" [loading]="true">
                <ng-template #header>
                    <tr>
                        <th style="width:25%">Code</th>
                        <th style="width:25%">Name</th>
                        <th style="width:25%">Category</th>
                        <th style="width:25%">Quantity</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [ProductService]
})
export class TableLoadingmaskDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }
}

loadingskeleton-doc

Skeleton 컴포넌트는 로딩 과정 동안 플레이스홀더로 사용할 수 있어요.

import { Component, OnInit } from '@angular/core';
import { SkeletonModule } from 'primeng/skeleton';
import { TableModule } from 'primeng/table';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-table [value]="products" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th>Code</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Quantity</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td><p-skeleton /></td>
                        <td><p-skeleton /></td>
                        <td><p-skeleton /></td>
                        <td><p-skeleton /></td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [SkeletonModule, TableModule]
})
export class TableLoadingskeletonDemo implements OnInit {
    products!: Product[];

    ngOnInit() {
        this.products = Array.from({ length: 10 }).map((_, i) => ({ id: i.toString() }));
    }
}

multiplecolumnssort-doc

sortMode를 multiple로 정의하면 여러 열을 정렬할 수 있어요. 이 모드에서는 헤더를 클릭할 때 metaKey(예: ⌘)를 누르고 있어야 해요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-table [value]="products" [tableStyle]="{ 'min-width': '60rem' }" sortMode="multiple">
                <ng-template #header>
                    <tr>
                        <th pSortableColumn="code" style="width:20%">
                            <div class="flex items-center gap-2">
                                Code
                                <p-sortIcon field="code" />
                            </div>
                        </th>
                        <th pSortableColumn="name" style="width:20%">
                            <div class="flex items-center gap-2">
                                Name
                                <p-sortIcon field="name" />
                            </div>
                        </th>
                        <th pSortableColumn="category" style="width:20%">
                            <div class="flex items-center gap-2">
                                Category
                                <p-sortIcon field="category" />
                            </div>
                        </th>
                        <th pSortableColumn="quantity" style="width:20%">
                            <div class="flex items-center gap-2">
                                Quantity
                                <p-sortIcon field="quantity" />
                            </div>
                        </th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [ProductService]
})
export class TableMultiplecolumnssortDemo implements OnInit {
    private productService = inject(ProductService);
    products: Product[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }
}

multipleselection-doc

selectionMode를 multiple로 설정하면 하나 이상의 행을 선택할 수 있어요. 기본적으로 다중 선택 모드에서는 기존 선택에 추가할 때 metaKey(예: ⌘)를 누를 필요가 없어요. 선택적인 metaKeySelection이 있으면 동작이 바뀌어서, 새 행을 선택하려면 meta 키를 누르고 있어야 해요. 터치 지원 기기에서는 DataTable이 항상 metaKey를 무시한다는 점에 유의하세요.

import { Component, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { TableModule } from 'primeng/table';
import { ToggleSwitchModule } from 'primeng/toggleswitch';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <div class="flex justify-center items-center mb-6 gap-2">
                <p-toggleswitch [(ngModel)]="metaKey" inputId="input-metakey" />
                <label for="input-metakey">MetaKey</label>
            </div>
            <p-table [value]="products" selectionMode="multiple" [(selection)]="selectedProducts" [metaKeySelection]="metaKey" dataKey="code" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th>Code</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Quantity</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product let-rowIndex="rowIndex">
                    <tr [pSelectableRow]="product" [pSelectableRowIndex]="rowIndex">
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule, ToggleSwitchModule, FormsModule],
    providers: [ProductService]
})
export class TableMultipleselectionDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];
    selectedProducts!: Product;
    metaKey: boolean = true;

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }
}

paginatorbasic-doc

paginator 속성을 true로 설정하고 rows 속성을 정의해 페이지당 행 수를 지정하면 페이지네이션이 활성화돼요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { CustomerService } from '@/service/customerservice';
import { Customer, Representative, Country } from '@/domain/customer';

@Component({
    template: `
        <div class="card">
            <p-table [value]="customers" [paginator]="true" [rows]="5" [tableStyle]="{ 'min-width': '50rem' }" [rowsPerPageOptions]="[5, 10, 20]">
                <ng-template #header>
                    <tr>
                        <th style="width:25%">Name</th>
                        <th style="width:25%">Country</th>
                        <th style="width:25%">Company</th>
                        <th style="width:25%">Representative</th>
                    </tr>
                </ng-template>
                <ng-template #body let-customer>
                    <tr>
                        <td>{{ customer.name }}</td>
                        <td>{{ customer.country.name }}</td>
                        <td>{{ customer.company }}</td>
                        <td>{{ customer.representative.name }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [CustomerService]
})
export class TablePaginatorbasicDemo implements OnInit {
    private customerService = inject(CustomerService);
    customers!: Customer[];

    ngOnInit() {
        this.customerService.getCustomersLarge().then((customers) => {
            this.customers = customers;
        });
    }
}

paginatorprogrammatic-doc

Paginator는 first 속성에 바인딩을 사용해 모델을 통해서도 제어할 수 있어요. 이 속성의 변경이 페이지네이션을 트리거해요.

import { Component, OnInit, inject } from '@angular/core';
import { ButtonModule } from 'primeng/button';
import { TableModule } from 'primeng/table';
import { CustomerService } from '@/service/customerservice';
import { Customer, Representative, Country } from '@/domain/customer';

@Component({
    template: `
        <div class="card">
            <div class="mb-4 flex gap-1">
                <p-button type="button" icon="pi pi-chevron-left" (click)="prev()" [disabled]="isFirstPage()" text />
                <p-button type="button" icon="pi pi-refresh" (click)="reset()" text />
                <p-button type="button" icon="pi pi-chevron-right" (click)="next()" [disabled]="isLastPage()" text />
            </div>
            <p-table
                [value]="customers"
                [paginator]="true"
                [rows]="rows"
                [showCurrentPageReport]="true"
                [first]="first"
                [tableStyle]="{ 'min-width': '50rem' }"
                currentPageReportTemplate="Showing {first} to {last} of {totalRecords} entries"
                (onPage)="pageChange($event)"
                [rowsPerPageOptions]="[10, 25, 50]"
            >
                <ng-template #header>
                    <tr>
                        <th style="width:25%">Name</th>
                        <th style="width:25%">Country</th>
                        <th style="width:25%">Company</th>
                        <th style="width:25%">Representative</th>
                    </tr>
                </ng-template>
                <ng-template #body let-customer>
                    <tr>
                        <td>{{ customer.name }}</td>
                        <td>{{ customer.country.name }}</td>
                        <td>{{ customer.company }}</td>
                        <td>{{ customer.representative.name }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [ButtonModule, TableModule],
    providers: [CustomerService]
})
export class TablePaginatorprogrammaticDemo implements OnInit {
    private customerService = inject(CustomerService);
    customers!: Customer[];
    first: number = 0;
    rows: number = 10;

    ngOnInit() {
        this.customerService.getCustomersLarge().then((customers) => {
            this.customers = customers;
        });
    }

    next() {
        this.first = this.first + this.rows;
    }

    prev() {
        this.first = this.first - this.rows;
    }

    reset() {
        this.first = 0;
    }

    pageChange(event) {
        this.first = event.first;
        this.rows = event.rows;
    }

    isLastPage(): boolean {
        return this.customers ? this.first + this.rows >= this.customers.length : true;
    }

    isFirstPage(): boolean {
        return this.customers ? this.first === 0 : true;
    }
}

presort-doc

기본 sortField와 sortOrder를 정의하면 단일 열 정렬에서 데이터가 처음부터 정렬된 상태로 표시돼요. 다중 정렬 모드에서는 대신 multiSortMeta를 사용해야 하며, 이때 DataTableSortMeta 객체의 배열을 제공하면 돼요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-table [value]="products" sortField="price" [sortOrder]="-1" [tableStyle]="{ 'min-width': '60rem' }">
                <ng-template #header>
                    <tr>
                        <th pSortableColumn="code" style="width:20%">
                            <div class="flex items-center gap-2">
                                Code
                                <p-sortIcon field="code" />
                            </div>
                        </th>
                        <th pSortableColumn="name" style="width:20%">
                            <div class="flex items-center gap-2">
                                Name
                                <p-sortIcon field="name" />
                            </div>
                        </th>
                        <th pSortableColumn="price" style="width:20%">
                            <div class="flex items-center gap-2">
                                Price
                                <p-sortIcon field="price" />
                            </div>
                        </th>
                        <th pSortableColumn="category" style="width:20%">
                            <div class="flex items-center gap-2">
                                Category
                                <p-sortIcon field="category" />
                            </div>
                        </th>
                        <th pSortableColumn="quantity" style="width:20%">
                            <div class="flex items-center gap-2">
                                Quantity
                                <p-sortIcon field="quantity" />
                            </div>
                        </th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.price | currency: 'USD' }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [ProductService]
})
export class TablePresortDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }
}

제품

Dialog를 활용한 CRUD 구현 예제예요.

import { Component, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ButtonModule } from 'primeng/button';
import { ConfirmDialogModule } from 'primeng/confirmdialog';
import { Dialog, DialogModule } from 'primeng/dialog';
import { SelectModule } from 'primeng/select';
import { FileUploadModule } from 'primeng/fileupload';
import { IconFieldModule } from 'primeng/iconfield';
import { InputIconModule } from 'primeng/inputicon';
import { InputNumberModule } from 'primeng/inputnumber';
import { RadioButtonModule } from 'primeng/radiobutton';
import { RatingModule } from 'primeng/rating';
import { Table, TableModule } from 'primeng/table';
import { TagModule } from 'primeng/tag';
import { ToastModule } from 'primeng/toast';
import { ToolbarModule } from 'primeng/toolbar';
import { InputTextModule } from 'primeng/inputtext';
import { ProductService } from '@/service/productservice';
import { MessageService, ConfirmationService } from 'primeng/api';
import { Product } from '@/domain/product';

interface Column {
    field: string;
    header: string;
    customExportHeader?: string;
}

interface ExportColumn {
    title: string;
    dataKey: string;
}

@Component({
    template: `
        <div class="card">
            <p-toast />
            <p-toolbar class="mb-6">
                <ng-template #start>
                    <p-button label="New" icon="pi pi-plus" class="mr-2" (onClick)="openNew()" />
                    <p-button severity="danger" label="Delete" icon="pi pi-trash" outlined (onClick)="deleteSelectedProducts()" [disabled]="!selectedProducts || !selectedProducts.length" />
                </ng-template>
                <ng-template #end>
                    <p-fileUpload mode="basic" accept="image/*" [maxFileSize]="1000000" label="Import" chooseLabel="Import" auto customUpload class="mr-2 inline-block" [chooseButtonProps]="{ severity: 'secondary' }" />
                    <p-button label="Export" icon="pi pi-upload" severity="secondary" (onClick)="exportCSV($event)" />
                </ng-template>
            </p-toolbar>
            <p-table
                #dt
                [value]="products"
                [rows]="10"
                [columns]="cols"
                [paginator]="true"
                [globalFilterFields]="['name', 'country.name', 'representative.name', 'status']"
                [tableStyle]="{ 'min-width': '75rem' }"
                [(selection)]="selectedProducts"
                [rowHover]="true"
                dataKey="id"
                currentPageReportTemplate="Showing {first} to {last} of {totalRecords} entries"
                [showCurrentPageReport]="true"
            >
                <ng-template #caption>
                    <div class="flex items-center justify-between">
                        <h5 class="m-0">Manage Products</h5>
                        <p-iconfield>
                            <p-inputicon class="pi pi-search" />
                            <input pInputText type="text" (input)="dt.filterGlobal($event.target.value, 'contains')" placeholder="Search..." />
                        </p-iconfield>
                    </div>
                </ng-template>
                <ng-template #header>
                    <tr>
                        <th style="width: 3rem">
                            <p-tableHeaderCheckbox />
                        </th>
                        <th style="min-width: 16rem">Code</th>
                        <th pSortableColumn="name" style="min-width:16rem">
                            <div class="flex items-center gap-2">
                                Name
                                <p-sortIcon field="name" />
                            </div>
                        </th>
                        <th>Image</th>
                        <th pSortableColumn="price" style="min-width: 8rem">
                            <div class="flex items-center gap-2">
                                Price
                                <p-sortIcon field="price" />
                            </div>
                        </th>
                        <th pSortableColumn="category" style="min-width:10rem">
                            <div class="flex items-center gap-2">
                                Category
                                <p-sortIcon field="category" />
                            </div>
                        </th>
                        <th pSortableColumn="rating" style="min-width: 12rem">
                            <div class="flex items-center gap-2">
                                Reviews
                                <p-sortIcon field="rating" />
                            </div>
                        </th>
                        <th pSortableColumn="inventoryStatus" style="min-width: 12rem">
                            <div class="flex items-center gap-2">
                                Status
                                <p-sortIcon field="inventoryStatus" />
                            </div>
                        </th>
                        <th style="min-width: 12rem"></th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td style="width: 3rem">
                            <p-tableCheckbox [value]="product" />
                        </td>
                        <td style="min-width: 12rem">{{ product.code }}</td>
                        <td style="min-width: 16rem">{{ product.name }}</td>
                        <td>
                            <img [src]="'https://primefaces.org/cdn/primeng/images/demo/product/' + product.image" [alt]="product.name" style="width: 64px" class="rounded" />
                        </td>
                        <td>{{ product.price | currency: 'USD' }}</td>
                        <td>{{ product.category }}</td>
                        <td>
                            <p-rating [(ngModel)]="product.rating" [readonly]="true" [cancel]="false" />
                        </td>
                        <td>
                            <p-tag [value]="product.inventoryStatus" [severity]="getSeverity(product.inventoryStatus)" />
                        </td>
                        <td>
                            <p-button icon="pi pi-pencil" class="mr-2" [rounded]="true" [outlined]="true" (click)="editProduct(product)" />
                            <p-button icon="pi pi-trash" severity="danger" [rounded]="true" [outlined]="true" (click)="deleteProduct(product)" />
                        </td>
                    </tr>
                </ng-template>
            </p-table>
            <p-dialog [(visible)]="productDialog" [style]="{ width: '450px' }" header="Product Details" [modal]="true">
                <ng-template #content>
                    <div class="flex flex-col gap-6">
                        <img [src]="'https://primefaces.org/cdn/primeng/images/demo/product/' + product.image" [alt]="product.image" class="block m-auto pb-4" *ngIf="product.image" />
                        <div>
                            <label for="name" class="block font-bold mb-3">Name</label>
                            <input type="text" pInputText id="name" [(ngModel)]="product.name" required autofocus fluid />
                            <small class="text-red-500" *ngIf="submitted && !product.name">Name is required.</small>
                        </div>
                        <div>
                            <label for="description" class="block font-bold mb-3">Description</label>
                            <textarea id="description" pTextarea [(ngModel)]="product.description" required rows="3" cols="20" fluid></textarea>
                        </div>
                        <div>
                            <label for="inventoryStatus" class="block font-bold mb-3">Inventory Status</label>
                            <p-select [(ngModel)]="product.inventoryStatus" inputId="inventoryStatus" [options]="statuses" optionLabel="label" optionValue="label" placeholder="Select a Status" fluid />
                        </div>
                        <div>
                            <span class="block font-bold mb-4">Category</span>
                            <div class="grid grid-cols-12 gap-4">
                                <div class="flex items-center gap-2 col-span-6">
                                    <p-radiobutton id="category1" name="category" value="Accessories" [(ngModel)]="product.category" />
                                    <label for="category1">Accessories</label>
                                </div>
                                <div class="flex items-center gap-2 col-span-6">
                                    <p-radiobutton id="category2" name="category" value="Clothing" [(ngModel)]="product.category" />
                                    <label for="category2">Clothing</label>
                                </div>
                                <div class="flex items-center gap-2 col-span-6">
                                    <p-radiobutton id="category3" name="category" value="Electronics" [(ngModel)]="product.category" />
                                    <label for="category3">Electronics</label>
                                </div>
                                <div class="flex items-center gap-2 col-span-6">
                                    <p-radiobutton id="category4" name="category" value="Fitness" [(ngModel)]="product.category" />
                                    <label for="category4">Fitness</label>
                                </div>
                            </div>
                        </div>
                        <div class="grid grid-cols-12 gap-4">
                            <div class="col-span-6">
                                <label for="price" class="block font-bold mb-3">Price</label>
                                <p-inputnumber id="price" [(ngModel)]="product.price" mode="currency" currency="USD" locale="en-US" fluid />
                            </div>
                            <div class="col-span-6">
                                <label for="quantity" class="block font-bold mb-3">Quantity</label>
                                <p-inputnumber id="quantity" [(ngModel)]="product.quantity" fluid />
                            </div>
                        </div>
                    </div>
                </ng-template>
                <ng-template #footer>
                    <p-button label="Cancel" icon="pi pi-times" text (click)="hideDialog()" />
                    <p-button label="Save" icon="pi pi-check" (click)="saveProduct()" />
                </ng-template>
            </p-dialog>
            <p-confirmdialog [style]="{ width: '450px' }" />
        </div>
    `,
    standalone: true,
    imports: [ButtonModule, ConfirmDialogModule, DialogModule, SelectModule, FileUploadModule, IconFieldModule, InputIconModule, InputNumberModule, RadioButtonModule, RatingModule, TableModule, TagModule, ToastModule, ToolbarModule, InputTextModule, FormsModule],
    providers: [ProductService, MessageService, ConfirmationService]
})
export class TableProductsDemo implements OnInit {
    private productService = inject(ProductService);
    private messageService = inject(MessageService);
    private confirmationService = inject(ConfirmationService);
    productDialog: boolean = false;
    products!: Product[];
    product!: Product;
    selectedProducts!: Product[] | null;
    submitted: boolean = false;
    statuses!: any[];
    cols!: Column[];
    exportColumns!: ExportColumn[];

    ngOnInit() {
        this.productService.getProducts().then((data) => {
            this.products = data;
        });
        this.statuses = [
            { label: 'INSTOCK', value: 'instock' },
            { label: 'LOWSTOCK', value: 'lowstock' },
            { label: 'OUTOFSTOCK', value: 'outofstock' }
        ];
        this.cols = [
            { field: 'code', header: 'Code', customExportHeader: 'Product Code' },
            { field: 'name', header: 'Name' },
            { field: 'image', header: 'Image' },
            { field: 'price', header: 'Price' },
            { field: 'category', header: 'Category' }
        ];
        this.exportColumns = this.cols.map((col) => ({ title: col.header, dataKey: col.field }));
    }

    openNew() {
        this.product = {};
        this.submitted = false;
        this.productDialog = true;
    }

    editProduct(product: Product) {
        this.product = { ...product };
        this.productDialog = true;
    }

    deleteSelectedProducts() {
        this.confirmationService.confirm({
            message: 'Are you sure you want to delete the selected products?',
            header: 'Confirm',
            icon: 'pi pi-exclamation-triangle',
            rejectButtonProps: {
                label: 'No',
                severity: 'secondary',
                variant: 'text'
            },
            acceptButtonProps: {
                severity: 'danger',
                label: 'Yes'
            },
            accept: () => {
                this.products = this.products.filter((val) => !this.selectedProducts?.includes(val));
                this.selectedProducts = null;
                this.messageService.add({
                    severity: 'success',
                    summary: 'Successful',
                    detail: 'Products Deleted',
                    life: 3000
                });
            }
        });
    }

    hideDialog() {
        this.productDialog = false;
        this.submitted = false;
    }

    deleteProduct(product: Product) {
        this.confirmationService.confirm({
            message: 'Are you sure you want to delete ' + product.name + '?',
            header: 'Confirm',
            icon: 'pi pi-exclamation-triangle',
            rejectButtonProps: {
                label: 'No',
                severity: 'secondary',
                variant: 'text'
            },
            acceptButtonProps: {
                severity: 'danger',
                label: 'Yes'
            },
            accept: () => {
                this.products = this.products.filter((val) => val.id !== product.id);
                this.product = {};
                this.messageService.add({
                    severity: 'success',
                    summary: 'Successful',
                    detail: 'Product Deleted',
                    life: 3000
                });
            }
        });
    }

    findIndexById(id: string): number {
        let index = -1;
        for (let i = 0; i < this.products.length; i++) {
            if (this.products[i].id === id) {
                index = i;
                break;
            }
        }
        
        return index;
    }

    createId(): string {
        let id = '';
        var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        for (var i = 0; i < 5; i++) {
            id += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return id;
    }

    getSeverity(status: string) {
        switch (status) {
            case 'INSTOCK':
                return 'success';
            case 'LOWSTOCK':
                return 'warn';
            case 'OUTOFSTOCK':
                return 'danger';
        }
    }

    saveProduct() {
        this.submitted = true;
        
        if (this.product.name?.trim()) {
            if (this.product.id) {
                this.products[this.findIndexById(this.product.id)] = this.product;
                this.messageService.add({
                    severity: 'success',
                    summary: 'Successful',
                    detail: 'Product Updated',
                    life: 3000
                });
            } else {
                this.product.id = this.createId();
                this.product.code = this.createId();
                this.product.image = 'product-placeholder.svg';
                this.products.push(this.product);
                this.messageService.add({
                    severity: 'success',
                    summary: 'Successful',
                    detail: 'Product Created',
                    life: 3000
                });
            }
        
            this.products = [...this.products];
            this.productDialog = false;
            this.product = {};
        }
    }
}

radiobuttonselection-doc

라디오 버튼을 사용해서 단일 선택을 처리할 수도 있어요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-table [value]="products" [(selection)]="selectedProduct" dataKey="code" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th style="width: 4rem"></th>
                        <th>Code</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Quantity</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td>
                            <p-tableRadioButton [value]="product" />
                        </td>
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [ProductService]
})
export class TableRadiobuttonselectionDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];
    selectedProduct!: Product;

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }
}

removablesort-doc

customSort 속성을 사용하면 제거 가능한 정렬을 구현할 수 있어요.

import { Component, OnInit, inject } from '@angular/core';
import { Table, TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { SortEvent } from 'primeng/api';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-table #dt [value]="products" (sortFunction)="customSort($event)" [customSort]="true">
                <ng-template #header>
                    <tr>
                        <th pSortableColumn="code">
                            <div class="flex items-center gap-2">
                                Code
                                <p-sortIcon field="code" />
                            </div>
                        </th>
                        <th pSortableColumn="name">
                            <div class="flex items-center gap-2">
                                Name
                                <p-sortIcon field="name" />
                            </div>
                        </th>
                        <th pSortableColumn="category">
                            <div class="flex items-center gap-2">
                                Category
                                <p-sortIcon field="category" />
                            </div>
                        </th>
                        <th pSortableColumn="quantity">
                            <div class="flex items-center gap-2">
                                Quantity
                                <p-sortIcon field="quantity" />
                            </div>
                        </th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [ProductService]
})
export class TableRemovablesortDemo implements OnInit {
    private productService = inject(ProductService);
    products: Product[];
    initialValue: Product[];
    isSorted: boolean = null;

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
            this.initialValue = [...data];
        });
    }

    customSort(event: SortEvent) {
        if (this.isSorted == null || this.isSorted === undefined) {
            this.isSorted = true;
            this.sortTableData(event);
        } else if (this.isSorted == true) {
            this.isSorted = false;
            this.sortTableData(event);
        } else if (this.isSorted == false) {
            this.isSorted = null;
            this.products = [...this.initialValue];
            this.dt.reset();
        }
    }

    sortTableData(event) {
        event.data.sort((data1, data2) => {
            let value1 = data1[event.field];
            let value2 = data2[event.field];
            let result = null;
            if (value1 == null && value2 != null) result = -1;
            else if (value1 != null && value2 == null) result = 1;
            else if (value1 == null && value2 == null) result = 0;
            else if (typeof value1 === 'string' && typeof value2 === 'string') result = value1.localeCompare(value2);
            else result = value1 < value2 ? -1 : value1 > value2 ? 1 : 0;
        
            return event.order * result;
        });
    }
}

재정렬

드래그 앤 드롭을 사용해서 컬럼과 행의 순서를 변경할 수 있어요. 컬럼 재정렬은 reorderableColumns 속성을 추가해서 설정해요. 마찬가지로 reorderableRows 속성을 추가하면 행을 드래그할 수 있게 돼요. 드래그 핸들로 사용하려면 컬럼에 rowReorder 속성이 있어야 하고, 재정렬이 완료된 후 행의 상태를 제어하려면 onRowReorder 콜백이 필요해요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

interface Column {
    field: string;
    header: string;
}

@Component({
    template: `
        <div class="card">
            <p-table [value]="products" [columns]="cols" [reorderableColumns]="true" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header let-columns>
                    <tr>
                        <th style="width:3rem"></th>
                        <th *ngFor="let col of columns" pReorderableColumn>
                            {{ col.header }}
                        </th>
                    </tr>
                </ng-template>
                <ng-template #body let-rowData let-columns="columns" let-index="rowIndex">
                    <tr [pReorderableRow]="index">
                        <td>
                            <span class="pi pi-bars" pReorderableRowHandle></span>
                        </td>
                        <td *ngFor="let col of columns">
                            {{ rowData[col.field] }}
                        </td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [ProductService]
})
export class TableReorderDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];
    cols!: Column[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
        this.cols = [
            { field: 'code', header: 'Code' },
            { field: 'name', header: 'Name' },
            { field: 'category', header: 'Category' },
            { field: 'quantity', header: 'Quantity' }
        ];
    }
}

rowedit-doc

행 편집(Row editing)은 행 안의 모든 에디터 가시성을 한 번에 토글하고, 편집을 저장하거나 취소하는 추가 옵션을 제공해요. 행 편집 기능은 table에 editMode를 "row"로 설정하고, 행을 고유하게 식별할 dataKey를 정의하고, 편집 가능한 행에 pEditableRow 디렉티브를 추가하고, UI 컨트롤을 각각 pInitEditableRow, pSaveEditableRow, pCancelEditableRow 디렉티브로 정의하면 활성화돼요. 저장과 취소 기능의 구현은 편집 비즈니스 로직을 더 세밀하게 제어할 수 있도록 페이지 작성자에게 맡겨져 있어요. 아래 예제는 편집이 초기화될 때 행을 복제하고, 편집 결과에 따라 저장하거나 복원하는 간단한 구현을 활용해요. "editing"이라는 암시적 변수가 body 템플릿에 전달되기 때문에, 유효성 검사 추가나 스타일링 같은 여러분만의 요구 사항에 맞춰 편집을 구현하는 자체 UI 컨트롤을 만들 수도 있어요. pSaveEditableRow는 유효성 검사 오류가 없을 때만 행을 다시 뷰 모드로 전환한다는 점에 유의하세요. 또한 특정 행의 편집을 비활성화하려면 pEditableRowDisabled 속성을 true로 설정하면 되고, 기본적으로 행을 편집 모드로 표시해야 하는 경우에는 editingRowKeys 속성을 사용하세요. 이 속성은 키가 레코드의 dataKey이고 값이 0보다 큰 임의의 숫자인 맵이에요.

import { Component, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { SelectModule } from 'primeng/select';
import { TableModule } from 'primeng/table';
import { TagModule } from 'primeng/tag';
import { ToastModule } from 'primeng/toast';
import { ButtonModule } from 'primeng/button';
import { InputTextModule } from 'primeng/inputtext';
import { RippleModule } from 'primeng/ripple';
import { ProductService } from '@/service/productservice';
import { SelectItem, MessageService } from 'primeng/api';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-toast />
            <p-table [value]="products" dataKey="id" editMode="row" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th style="width:22%">Code</th>
                        <th style="width:22%">Name</th>
                        <th style="width:22%">Inventory Status</th>
                        <th style="width:22%">Price</th>
                        <th style="width:12%"></th>
                    </tr>
                </ng-template>
                <ng-template #body let-product let-editing="editing" let-ri="rowIndex">
                    <tr [pEditableRow]="product">
                        <td>
                            <p-cellEditor>
                                <ng-template #input>
                                    <input pInputText type="text" [(ngModel)]="product.code" />
                                </ng-template>
                                <ng-template #output>
                                    {{ product.code }}
                                </ng-template>
                            </p-cellEditor>
                        </td>
                        <td>
                            <p-cellEditor>
                                <ng-template #input>
                                    <input pInputText type="text" [(ngModel)]="product.name" required />
                                </ng-template>
                                <ng-template #output>
                                    {{ product.name }}
                                </ng-template>
                            </p-cellEditor>
                        </td>
                        <td>
                            <p-cellEditor>
                                <ng-template #input>
                                    <p-select [options]="statuses" appendTo="body" [(ngModel)]="product.inventoryStatus" [style]="{ width: '100%' }" />
                                </ng-template>
                                <ng-template #output>
                                    <p-tag [value]="product.inventoryStatus" [severity]="getSeverity(product.inventoryStatus)" />
                                </ng-template>
                            </p-cellEditor>
                        </td>
                        <td>
                            <p-cellEditor>
                                <ng-template #input>
                                    <input pInputText type="text" [(ngModel)]="product.price" />
                                </ng-template>
                                <ng-template #output>
                                    {{ product.price | currency: 'USD' }}
                                </ng-template>
                            </p-cellEditor>
                        </td>
                        <td>
                            <div class="flex items-center justify-center gap-2">
                                <button *ngIf="!editing" pButton pRipple type="button" pInitEditableRow icon="pi pi-pencil" (click)="onRowEditInit(product)" text rounded severity="secondary"></button>
                                <button *ngIf="editing" pButton pRipple type="button" pSaveEditableRow icon="pi pi-check" (click)="onRowEditSave(product)" text rounded severity="secondary"></button>
                                <button *ngIf="editing" pButton pRipple type="button" pCancelEditableRow icon="pi pi-times" (click)="onRowEditCancel(product, ri)" text rounded severity="secondary"></button>
                            </div>
                        </td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [SelectModule, TableModule, TagModule, ToastModule, ButtonModule, InputTextModule, RippleModule, FormsModule],
    providers: [ProductService, MessageService]
})
export class TableRoweditDemo implements OnInit {
    private productService = inject(ProductService);
    private messageService = inject(MessageService);
    products!: Product[];
    statuses!: SelectItem[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
        this.statuses = [
            { label: 'In Stock', value: 'INSTOCK' },
            { label: 'Low Stock', value: 'LOWSTOCK' },
            { label: 'Out of Stock', value: 'OUTOFSTOCK' }
        ];
    }

    onRowEditInit(product: Product) {
        this.clonedProducts[product.id as string] = { ...product };
    }

    onRowEditSave(product: Product) {
        if (product.price > 0) {
            delete this.clonedProducts[product.id as string];
            this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Product is updated' });
        } else {
            this.messageService.add({ severity: 'error', summary: 'Error', detail: 'Invalid Price' });
        }
    }

    onRowEditCancel(product: Product, index: number) {
        this.products[index] = this.clonedProducts[product.id as string];
        delete this.clonedProducts[product.id as string];
    }

    getSeverity(status: string) {
        switch (status) {
            case 'INSTOCK':
                return 'success';
            case 'LOWSTOCK':
                return 'warn';
            case 'OUTOFSTOCK':
                return 'danger';
        }
    }
}

rowexpansion-doc

행 확장(row expansion)은 특정 행에 대한 상세 콘텐츠를 표시할 수 있게 해줘요. 이 기능을 사용하려면 dataKey를 정의하고, expandedrow라는 이름의 템플릿을 추가한 다음, 확장을 토글하는 대상이 될 요소에 pRowToggler 디렉티브를 사용하세요. 이를 통해 버튼, 링크 등 자신만의 커스텀 UI를 제공할 수 있어요. 아래 예제에서는 아이콘이 있는 앵커를 토글러로 사용해요. pRowTogglerDisabled를 true로 설정하면 해당 요소의 토글 이벤트가 비활성화돼요.

import { Component, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ButtonModule } from 'primeng/button';
import { RatingModule } from 'primeng/rating';
import { TableModule } from 'primeng/table';
import { TagModule } from 'primeng/tag';
import { ToastModule } from 'primeng/toast';
import { RippleModule } from 'primeng/ripple';
import { ProductService } from '@/service/productservice';
import { MessageService } from 'primeng/api';
import { Product } from '@/domain/product';
import { Customer } from '@/domain/customer';

@Component({
    template: `
        <div class="card">
            <p-toast />
            <p-table [value]="products" dataKey="id" [tableStyle]="{ 'min-width': '60rem' }" [expandedRowKeys]="expandedRows" (onRowExpand)="onRowExpand($event)" (onRowCollapse)="onRowCollapse($event)">
                <ng-template #caption>
                    <div class="flex flex-wrap justify-end gap-2">
                        <p-button label="Expand All" icon="pi pi-plus" text (onClick)="expandAll()" />
                        <p-button label="Collapse All" icon="pi pi-minus" text (onClick)="collapseAll()" />
                    </div>
                </ng-template>
                <ng-template #header>
                    <tr>
                        <th style="width: 5rem"></th>
                        <th>Name</th>
                        <th>Image</th>
                        <th>Price</th>
                        <th>Category</th>
                        <th>Reviews</th>
                        <th>Status</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product let-expanded="expanded">
                    <tr>
                        <td>
                            <p-button type="button" pRipple [pRowToggler]="product" [text]="true" severity="secondary" [rounded]="true" [icon]="expanded ? 'pi pi-chevron-down' : 'pi pi-chevron-right'" />
                        </td>
                        <td>{{ product.name }}</td>
                        <td>
                            <img [src]="'https://primefaces.org/cdn/primeng/images/demo/product/' + product.image" [alt]="product.name" width="50" class="shadow-lg" />
                        </td>
                        <td>{{ product.price | currency: 'USD' }}</td>
                        <td>{{ product.category }}</td>
                        <td>
                            <p-rating [(ngModel)]="product.rating" [readonly]="true" [cancel]="false" />
                        </td>
                        <td>
                            <p-tag [value]="product.inventoryStatus" [severity]="getSeverity(product.inventoryStatus)" />
                        </td>
                    </tr>
                </ng-template>
                <ng-template #expandedrow let-product>
                    <tr>
                        <td colspan="7">
                            <div class="p-4">
                                <h5>Orders for {{ product.name }}</h5>
                                <p-table [value]="product.orders" dataKey="id">
                                    <ng-template #header>
                                        <tr>
                                            <th pSortableColumn="id">
                                                <div class="flex items-center gap-2">
                                                    Id
                                                    <p-sortIcon field="price" />
                                                </div>
                                            </th>
                                            <th pSortableColumn="customer">
                                                <div class="flex items-center gap-2">
                                                    Customer
                                                    <p-sortIcon field="customer" />
                                                </div>
                                            </th>
                                            <th pSortableColumn="date">
                                                <div class="flex items-center gap-2">
                                                    Date
                                                    <p-sortIcon field="date" />
                                                </div>
                                            </th>
                                            <th pSortableColumn="amount">
                                                <div class="flex items-center gap-2">
                                                    Amount
                                                    <p-sortIcon field="amount" />
                                                </div>
                                            </th>
                                            <th pSortableColumn="status">
                                                <div class="flex items-center gap-2">
                                                    Status
                                                    <p-sortIcon field="status" />
                                                </div>
                                            </th>
                                            <th style="width: 4rem"></th>
                                        </tr>
                                    </ng-template>
                                    <ng-template #body let-order>
                                        <tr>
                                            <td>{{ order.id }}</td>
                                            <td>{{ order.customer }}</td>
                                            <td>{{ order.date }}</td>
                                            <td>{{ order.amount | currency: 'USD' }}</td>
                                            <td>
                                                <p-tag [value]="order.status" [severity]="getStatusSeverity(order.status)" />
                                            </td>
                                            <td>
                                                <p-button type="button" icon="pi pi-search" />
                                            </td>
                                        </tr>
                                    </ng-template>
                                    <ng-template #emptymessage>
                                        <tr>
                                            <td colspan="6">There are no order for this product yet.</td>
                                        </tr>
                                    </ng-template>
                                </p-table>
                            </div>
                        </td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [ButtonModule, RatingModule, TableModule, TagModule, ToastModule, RippleModule, FormsModule],
    providers: [ProductService, MessageService]
})
export class TableRowexpansionDemo implements OnInit {
    private productService = inject(ProductService);
    private messageService = inject(MessageService);
    products!: Product[];
    expandedRows: any = {};

    ngOnInit() {
        this.productService.getProductsWithOrdersSmall().then((data) => {
            this.products = data;
        });
    }

    expandAll() {
        this.expandedRows = this.products.reduce((acc, p) => (acc[p.id] = true) && acc, {});
    }

    collapseAll() {
        this.expandedRows = {};
    }

    getSeverity(status: string) {
        switch (status) {
            case 'INSTOCK':
                return 'success';
            case 'LOWSTOCK':
                return 'warn';
            case 'OUTOFSTOCK':
                return 'danger';
        }
    }

    getStatusSeverity(status: string) {
        switch (status) {
            case 'PENDING':
                return 'warn';
            case 'DELIVERED':
                return 'success';
            case 'CANCELLED':
                return 'danger';
        }
    }

    onRowExpand(event: TableRowExpandEvent) {
        this.messageService.add({ severity: 'info', summary: 'Product Expanded', detail: event.data.name, life: 3000 });
    }

    onRowCollapse(event: TableRowCollapseEvent) {
        this.messageService.add({
            severity: 'success',
            summary: 'Product Collapsed',
            detail: event.data.name,
            life: 3000
        });
    }
}

rowspangrouping-doc

rowGroupMode가 rowspan으로 설정되면 그룹화 컬럼이 여러 행에 걸쳐 표시돼요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { TagModule } from 'primeng/tag';
import { CustomerService } from '@/service/customerservice';
import { Customer, Representative, Country } from '@/domain/customer';

@Component({
    template: `
        <div class="card">
            <p-table [value]="customers" rowGroupMode="rowspan" groupRowsBy="representative.name" sortField="representative.name" sortMode="single" [tableStyle]="{ 'min-width': '75rem' }">
                <ng-template #header>
                    <tr>
                        <th style="width:3rem">#</th>
                        <th>Representative</th>
                        <th>Name</th>
                        <th>Country</th>
                        <th>Company</th>
                        <th>Status</th>
                    </tr>
                </ng-template>
                <ng-template #body let-customer let-rowIndex="rowIndex" let-rowgroup="rowgroup" let-rowspan="rowspan">
                    <tr>
                        <td>{{ rowIndex }}</td>
                        <td *ngIf="rowgroup" [attr.rowspan]="rowspan">
                            <div class="flex items-center gap-2">
                                <img [alt]="customer.representative.name" src="https://primefaces.org/cdn/primeng/images/demo/avatar/{{ customer.representative.image }}" width="32" />
                                <span>{{ customer.representative.name }}</span>
                            </div>
                        </td>
                        <td>
                            {{ customer.name }}
                        </td>
                        <td>
                            <div class="flex items-center gap-2">
                                <img src="https://primefaces.org/cdn/primeng/images/demo/flag/flag_placeholder.png" [class]="'flag flag-' + customer.country.code" style="width: 20px" />
                                <span>{{ customer.country.name }}</span>
                            </div>
                        </td>
                        <td>
                            {{ customer.company }}
                        </td>
                        <td>
                            <p-tag [value]="customer.status" [severity]="getSeverity(customer.status)" />
                        </td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule, TagModule],
    providers: [CustomerService]
})
export class TableRowspangroupingDemo implements OnInit {
    private customerService = inject(CustomerService);
    customers!: Customer[];

    ngOnInit() {
        this.customerService.getCustomersMedium().then((data) => {
            this.customers = data;
        });
    }

    calculateCustomerTotal(name: string) {
        let total = 0;
        
        if (this.customers) {
            for (let customer of this.customers) {
                if (customer.representative?.name === name) {
                    total++;
                }
            }
        }
        
        return total;
    }

    getSeverity(status: string) {
        switch (status) {
            case 'unqualified':
                return 'danger';
        
            case 'qualified':
                return 'success';
        
            case 'new':
                return 'info';
        
            case 'negotiation':
                return 'warn';
        
            case 'renewal':
                return null;
        }
    }
}

selectionevents-doc

테이블은 선택 이벤트를 리스닝할 수 있도록 onRowSelect와 onRowUnselect 이벤트를 제공해요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { ToastModule } from 'primeng/toast';
import { ProductService } from '@/service/productservice';
import { MessageService } from 'primeng/api';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-toast />
            <p-table [value]="products" selectionMode="single" [(selection)]="selectedProduct" dataKey="code" (onRowSelect)="onRowSelect($event)" (onRowUnselect)="onRowUnselect($event)" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th>Code</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Quantity</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr [pSelectableRow]="product">
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule, ToastModule],
    providers: [ProductService, MessageService]
})
export class TableSelectioneventsDemo implements OnInit {
    private productService = inject(ProductService);
    private messageService = inject(MessageService);
    products!: Product[];
    selectedProduct!: Product;

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }

    onRowSelect(event: any) {
        this.messageService.add({ severity: 'info', summary: 'Product Selected', detail: event.data.name });
    }

    onRowUnselect(event: any) {
        this.messageService.add({ severity: 'info', summary: 'Product Unselected', detail: event.data.name });
    }
}

singlecolumnsort-doc

pSortableColumn 디렉티브를 추가하면 컬럼을 정렬 가능하게 만들 수 있어요. 이 디렉티브의 값은 정렬 기준이 되는 필드이고, p-sortIcon 컴포넌트로 정렬 표시기를 제공해요. 동적 컬럼의 경우 pSortableColumnDisabled 속성을 true로 설정하면 해당 컬럼의 정렬이 비활성화돼요. 기본 정렬은 단일 컬럼에서 실행되는데, 여러 필드 정렬을 활성화하려면 sortMode 속성을 "multiple"로 설정하고 다른 컬럼을 클릭할 때 metakey를 사용하세요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-table [value]="products" [tableStyle]="{ 'min-width': '60rem' }">
                <ng-template #header>
                    <tr>
                        <th pSortableColumn="code" style="width:20%">
                            <div class="flex items-center gap-2">
                                Code
                                <p-sortIcon field="code" />
                            </div>
                        </th>
                        <th pSortableColumn="name" style="width:20%">
                            <div class="flex items-center gap-2">
                                Name
                                <p-sortIcon field="name" />
                            </div>
                        </th>
                        <th pSortableColumn="category" style="width:20%">
                            <div class="flex items-center gap-2">
                                Category
                                <p-sortIcon field="category" />
                            </div>
                        </th>
                        <th pSortableColumn="quantity" style="width:20%">
                            <div class="flex items-center gap-2">
                                Quantity
                                <p-sortIcon field="quantity" />
                            </div>
                        </th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [ProductService]
})
export class TableSinglecolumnsortDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }
}

singleselection-doc

selectionMode를 single로 정의하고 selection 속성으로 값 바인딩을 하면 단일 행 선택이 활성화돼요. 가능하다면 성능 최적화를 위해 dataKey로 행의 고유 식별자를 제공하는 게 좋아요. 기본적으로 행 선택을 해제하려면 metaKey(예: ⌘)를 눌러야 하지만, metaKeySelection 속성을 비활성화해서 이 동작을 설정할 수 있어요. 터치 지원 기기에서는 이 옵션이 효과가 없으며 false로 설정했을 때와 동일하게 동작해요.

import { Component, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { TableModule } from 'primeng/table';
import { ToggleSwitchModule } from 'primeng/toggleswitch';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <div class="flex justify-center items-center mb-6 gap-2">
                <p-toggleswitch [(ngModel)]="metaKey" inputId="input-metakey" />
                <label for="input-metakey">MetaKey</label>
            </div>
            <p-table [value]="products" selectionMode="single" [(selection)]="selectedProduct" [metaKeySelection]="metaKey" dataKey="id" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th>Code</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Quantity</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr [pSelectableRow]="product">
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule, ToggleSwitchModule, FormsModule],
    providers: [ProductService]
})
export class TableSingleselectionDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];
    selectedProduct!: Product;
    metaKey: boolean = true;

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }
}

Size

일반 테이블 외에도 다른 크기의 대안 테이블을 사용할 수 있어요.

import { Component, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { SelectButtonModule } from 'primeng/selectbutton';
import { TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <div class="flex justify-center mb-4">
                <p-selectbutton [options]="sizes" [(ngModel)]="selectedSize" [multiple]="false" optionLabel="name" optionValue="value" />
            </div>
            <p-table [value]="products" [tableStyle]="{ 'min-width': '50rem' }" [size]="selectedSize">
                <ng-template #header>
                    <tr>
                        <th>Code</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Quantity</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [SelectButtonModule, TableModule, FormsModule],
    providers: [ProductService]
})
export class TableSizeDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];
    sizes!: any[];
    selectedSize: any = undefined;

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
        this.sizes = [
            { name: 'Small', value: 'small' },
            { name: 'Normal', value: undefined },
            { name: 'Large', value: 'large' }
        ];
    }
}

상태 유지

Stateful 테이블은 페이지, 정렬, 필터링 같은 상태를 로컬 스토리지나 세션 스토리지에 보관할 수 있어서, 페이지를 다시 방문하면 테이블이 마지막 설정을 사용해 데이터를 렌더링해요. 이 기능을 테스트하려면 테이블의 상태를 변경해 보세요(예: 페이지네이션), 다른 페이지로 이동했다가 이 테이블로 다시 돌아오세요. stateStorage 속성이 session으로 설정되어 있어서 브라우저를 닫을 때까지 Table이 상태를 유지해요. 다른 대안은 local인데, 더 오래 유지되도록 localStorage를 참조하는 방식이에요.

import { Component, OnInit, inject } from '@angular/core';
import { IconFieldModule } from 'primeng/iconfield';
import { InputIconModule } from 'primeng/inputicon';
import { Table, TableModule } from 'primeng/table';
import { TagModule } from 'primeng/tag';
import { InputTextModule } from 'primeng/inputtext';
import { CustomerService } from '@/service/customerservice';
import { Customer, Representative, Country } from '@/domain/customer';

@Component({
    template: `
        <div class="card">
            <p-table
                #dt1
                [value]="customers"
                [globalFilterFields]="['name', 'country.name', 'representative.name', 'status']"
                selectionMode="single"
                [(selection)]="selectedCustomers"
                dataKey="id"
                [tableStyle]="{ 'min-width': '50rem' }"
                [rows]="5"
                [paginator]="true"
                stateStorage="session"
                stateKey="statedemo-session"
            >
                <ng-template #caption>
                    <p-iconfield iconPosition="left">
                        <p-inputicon>
                            <i class="pi pi-search"></i>
                        </p-inputicon>
                        <input pInputText type="text" [value]="dt1.filters['global']?.value" (input)="dt1.filterGlobal($event.target.value, 'contains')" placeholder="Global Search" />
                    </p-iconfield>
                </ng-template>
                <ng-template #header>
                    <tr>
                        <th pSortableColumn="name" style="width:25%">
                            <div class="flex items-center gap-2">
                                Name
                                <p-sortIcon field="name" />
                            </div>
                        </th>
                        <th pSortableColumn="country.name" style="width:25%">
                            <div class="flex items-center gap-2">
                                Country
                                <p-sortIcon field="country.name" />
                            </div>
                        </th>
                        <th pSortableColumn="representative.name" style="width:25%">
                            <div class="flex items-center gap-2">
                                Representative
                                <p-sortIcon field="representative.name" />
                            </div>
                        </th>
                        <th pSortableColumn="status" style="width:25%">
                            <div class="flex items-center gap-2">
                                Status
                                <p-sortIcon field="status" />
                            </div>
                        </th>
                    </tr>
                </ng-template>
                <ng-template #body let-customer>
                    <tr [pSelectableRow]="customer">
                        <td>
                            {{ customer.name }}
                        </td>
                        <td>
                            <div class="flex items-center gap-2">
                                <img src="https://primefaces.org/cdn/primeng/images/demo/flag/flag_placeholder.png" [class]="'flag flag-' + customer.country.code" style="width: 20px" />
                                <span class="ml-1 align-middle">{{ customer.country.name }}</span>
                            </div>
                        </td>
                        <td>
                            <div class="flex items-center gap-2">
                                <img [alt]="customer.representative.name" src="https://primefaces.org/cdn/primeng/images/demo/avatar/{{ customer.representative.image }}" width="32" style="vertical-align: middle" />
                                <span class="ml-1 align-middle">{{ customer.representative.name }}</span>
                            </div>
                        </td>
                        <td>
                            <p-tag [value]="customer.status" [severity]="getSeverity(customer.status)" />
                        </td>
                    </tr>
                </ng-template>
                <ng-template #body let-customer>
                    <tr [pSelectableRow]="customer">
                        <td>
                            {{ customer.name }}
                        </td>
                        <td>
                            <img src="https://primefaces.org/cdn/primeng/images/demo/flag/flag_placeholder.png" [class]="'flag flag-' + customer.country.code" style="width: 20px" />
                            <span class="ml-1 align-middle">{{ customer.country.name }}</span>
                        </td>
                        <td>
                            <img [alt]="customer.representative.name" src="https://primefaces.org/cdn/primeng/images/demo/avatar/{{ customer.representative.image }}" width="32" style="vertical-align: middle" />
                            <span class="ml-1 align-middle">{{ customer.representative.name }}</span>
                        </td>
                        <td>
                            <p-tag [value]="customer.status" [severity]="getSeverity(customer.status)" />
                        </td>
                    </tr>
                </ng-template>
                <ng-template #emptymessage>
                    <tr>
                        <td colspan="4">No customers found.</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [IconFieldModule, InputIconModule, TableModule, TagModule, InputTextModule],
    providers: [CustomerService]
})
export class TableStatefulDemo implements OnInit {
    private customerService = inject(CustomerService);
    customers!: Customer[];
    selectedCustomers!: Customer;

    ngOnInit() {
        this.customerService.getCustomersSmall().then((data) => {
            this.customers = data;
        });
    }
}

줄무늬 행

stripedRows 속성이 있으면 행이 교대로 표시돼요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

@Component({
    template: `
        <div class="card">
            <p-table [value]="products" stripedRows [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th>Code</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Quantity</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td>{{ product.code }}</td>
                        <td>{{ product.name }}</td>
                        <td>{{ product.category }}</td>
                        <td>{{ product.quantity }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [ProductService]
})
export class TableStripedDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
    }
}

style-doc

특정 행이나 셀은 조건에 따라 쉽게 스타일링할 수 있어요.

styling-doc

import { Component } from '@angular/core';

@Component({
    template: `
        <div class="doc-tablewrapper">
            <table class="doc-table">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Element</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>p-datatable</td>
                        <td>Container element.</td>
                    </tr>
                    <tr>
                        <td>p-datatable-header</td>
                        <td>Header section.</td>
                    </tr>
                    <tr>
                        <td>p-datatable-footer</td>
                        <td>Footer section.</td>
                    </tr>
                    <tr>
                        <td>p-sortable-column</td>
                        <td>Sortable column header.</td>
                    </tr>
                    <tr>
                        <td>p-editable-column</td>
                        <td>Editable column cell.</td>
                    </tr>
                    <tr>
                        <td>p-datatable-thead</td>
                        <td>Thead element of header columns.</td>
                    </tr>
                    <tr>
                        <td>p-datatable-tbody</td>
                        <td>Tbody element of body rows.</td>
                    </tr>
                    <tr>
                        <td>p-datatable-tfoot</td>
                        <td>Tfoot element of footer columns.</td>
                    </tr>
                    <tr>
                        <td>p-datatable-scrollable</td>
                        <td>Container element when scrolling is enabled.</td>
                    </tr>
                    <tr>
                        <td>p-datatable-resizable</td>
                        <td>Container element when column resizing is enabled.</td>
                    </tr>
                    <tr>
                        <td>p-datatable-resizable-fit</td>
                        <td>Container element when column resizing is enabled and set to fit mode.</td>
                    </tr>
                    <tr>
                        <td>p-column-resizer-helper</td>
                        <td>Vertical resizer indicator bar.</td>
                    </tr>
                    <tr>
                        <td>p-datatable-reorderablerow-handle</td>
                        <td>Handle element of a reorderable row.</td>
                    </tr>
                    <tr>
                        <td>p-datatable-reorder-indicator-up</td>
                        <td>Up indicator to display during column reordering.</td>
                    </tr>
                    <tr>
                        <td>p-datatable-reorder-indicator-up</td>
                        <td>Down indicator to display during column reordering.</td>
                    </tr>
                    <tr>
                        <td>p-datatable-loading-overlay</td>
                        <td>Overlay to display when table is loading.</td>
                    </tr>
                    <tr>
                        <td>p-datatable-loading-icon</td>
                        <td>Icon to display when table is loading.</td>
                    </tr>
                </tbody>
            </table>
        </div>
    `,
    standalone: true,
    imports: []
})
export class TableStylingDemo {}

subheadergrouping-doc

행은 groupRowsBy 속성으로 그룹화돼요. rowGroupMode가 subheader로 설정되면 각 그룹마다 헤더와 푸터를 표시할 수 있어요. 그룹 헤더의 내용은 groupheader 템플릿으로, 푸터의 내용은 groupfooter 템플릿으로 제공돼요.

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { TagModule } from 'primeng/tag';
import { CustomerService } from '@/service/customerservice';
import { Customer, Country } from '@/domain/customer';

@Component({
    template: `
        <div class="card">
            <p-table [value]="customers" sortField="representative.name" sortMode="single" [scrollable]="true" scrollHeight="400px" rowGroupMode="subheader" groupRowsBy="representative.name" [tableStyle]="{ 'min-width': '60rem' }">
                <ng-template #header>
                    <tr>
                        <th>Name</th>
                        <th>Country</th>
                        <th>Company</th>
                        <th>Status</th>
                        <th>Date</th>
                    </tr>
                </ng-template>
                <ng-template #groupheader let-customer>
                    <tr pRowGroupHeader>
                        <td colspan="5">
                            <div class="flex items-center gap-2">
                                <img [alt]="customer.representative.name" src="https://primefaces.org/cdn/primeng/images/demo/avatar/{{ customer.representative.image }}" width="32" style="vertical-align: middle" />
                                <span class="font-bold">{{ customer.representative.name }}</span>
                            </div>
                        </td>
                    </tr>
                </ng-template>
                <ng-template #groupfooter let-customer>
                    <tr>
                        <td colspan="5">
                            <div class="text-right font-bold pe-12">Total Customers: {{ calculateCustomerTotal(customer.representative.name) }}</div>
                        </td>
                    </tr>
                </ng-template>
                <ng-template #body let-customer let-rowIndex="rowIndex">
                    <tr>
                        <td>
                            {{ customer.name }}
                        </td>
                        <td>
                            <div class="flex items-center gap-2">
                                <img src="https://primefaces.org/cdn/primeng/images/demo/flag/flag_placeholder.png" [class]="'flag flag-' + customer.country.code" style="width: 20px" />
                                <span>{{ customer.country.name }}</span>
                            </div>
                        </td>
                        <td>
                            {{ customer.company }}
                        </td>
                        <td>
                            <p-tag [value]="customer.status" [severity]="getSeverity(customer.status)" />
                        </td>
                        <td>
                            {{ customer.date }}
                        </td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule, TagModule],
    providers: [CustomerService]
})
export class TableSubheadergroupingDemo implements OnInit {
    private customerService = inject(CustomerService);
    customers!: Customer[];

    ngOnInit() {
        this.customerService.getCustomersMedium().then((data) => {
            this.customers = data;
        });
    }

    calculateCustomerTotal(name: string) {
        let total = 0;
        
        if (this.customers) {
            for (let customer of this.customers) {
                if (customer.representative?.name === name) {
                    total++;
                }
            }
        }
        
        return total;
    }

    getSeverity(status: string) {
        switch (status) {
            case 'unqualified':
                return 'danger';
        
            case 'qualified':
                return 'success';
        
            case 'new':
                return 'info';
        
            case 'negotiation':
                return 'warn';
        
            case 'renewal':
                return null;
        }
    }
}

템플릿

header, body, footer 섹션의 사용자 정의 콘텐츠는 템플릿을 통해 지원돼요.

import { Component, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ButtonModule } from 'primeng/button';
import { RatingModule } from 'primeng/rating';
import { TableModule } from 'primeng/table';
import { TagModule } from 'primeng/tag';
import { ProductService } from '@/service/productservice';
import { Product } from '@/domain/product';

interface Column {
    field: string;
    header: string;
}

@Component({
    template: `
        <div class="card">
            <p-table [value]="products" [tableStyle]="{ 'min-width': '60rem' }">
                <ng-template #caption>
                    <div class="flex items-center justify-between">
                        <span class="text-xl font-bold">Products</span>
                        <p-button icon="pi pi-refresh" rounded raised />
                    </div>
                </ng-template>
                <ng-template #header>
                    <tr>
                        <th>Name</th>
                        <th>Image</th>
                        <th>Price</th>
                        <th>Category</th>
                        <th>Reviews</th>
                        <th>Status</th>
                    </tr>
                </ng-template>
                <ng-template #body let-product>
                    <tr>
                        <td>{{ product.name }}</td>
                        <td>
                            <img [src]="'https://primefaces.org/cdn/primeng/images/demo/product/' + product.image" [alt]="product.name" class="w-24 rounded" />
                        </td>
                        <td>{{ product.price | currency: 'USD' }}</td>
                        <td>{{ product.category }}</td>
                        <td><p-rating [(ngModel)]="product.rating" [readonly]="true" [cancel]="false" /></td>
                        <td>
                            <p-tag [value]="product.inventoryStatus" [severity]="getSeverity(product.inventoryStatus)" />
                        </td>
                    </tr>
                </ng-template>
                <ng-template #footer>
                    <tr>
                        <td colspan="6">In total there are {{ products ? products.length : 0 }} products.</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [ButtonModule, RatingModule, TableModule, TagModule, FormsModule],
    providers: [ProductService]
})
export class TableTemplateDemo implements OnInit {
    private productService = inject(ProductService);
    products!: Product[];
    cols!: Column[];

    ngOnInit() {
        this.productService.getProductsMini().then((data) => {
            this.products = data;
        });
        this.cols = [
            { field: 'code', header: 'Code' },
            { field: 'name', header: 'Name' },
            { field: 'category', header: 'Category' },
            { field: 'quantity', header: 'Quantity' }
        ];
    }

    getSeverity(status: string) {
        switch (status) {
            case 'INSTOCK':
                return 'success';
            case 'LOWSTOCK':
                return 'warn';
            case 'OUTOFSTOCK':
                return 'danger';
        }
    }
}

verticalscroll-doc

import { Component, OnInit, inject } from '@angular/core';
import { TableModule } from 'primeng/table';
import { CustomerService } from '@/service/customerservice';
import { Customer, Representative, Country } from '@/domain/customer';

@Component({
    template: `
        <div class="card">
            <p-table [value]="customers" [scrollable]="true" scrollHeight="400px" [tableStyle]="{ 'min-width': '50rem' }">
                <ng-template #header>
                    <tr>
                        <th>Name</th>
                        <th>Country</th>
                        <th>Company</th>
                        <th>Representative</th>
                    </tr>
                </ng-template>
                <ng-template #body let-customer let-index="index">
                    <tr>
                        <td>{{ customer.name }}</td>
                        <td>{{ customer.country.name }}</td>
                        <td>{{ customer.company }}</td>
                        <td>{{ customer.representative.name }}</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [CustomerService]
})
export class TableVerticalscrollDemo implements OnInit {
    private customerService = inject(CustomerService);
    customers!: Customer[];

    ngOnInit() {
        this.customerService.getCustomersMedium().then((data) => {
            this.customers = data;
        });
    }
}

virtualscroll-doc

가상 스크롤링(Virtual Scrolling)은 대량의 데이터를 렌더링하는 효율적인 방법이에요. 사용법은 일반 스크롤링과 비슷한데, 고정된 itemSize를 정의하기 위해 virtualScrollerOptions 속성을 추가로 사용한다는 점이 달라요. 내부적으로는 VirtualScroller 컴포넌트가 활용되기 때문에, 사용 가능한 옵션에 대한 자세한 정보는 VirtualScroller의 API를 참고하세요. 이 예제에서는 미리 로드된 10000개의 레코드가 Table로 렌더링돼요.

import { Component, OnInit, inject } from '@angular/core';
import { Table, TableModule } from 'primeng/table';
import { CarService } from '@/service/carservice';
import { Car } from '@/domain/car';

interface Column {
    field: string;
    header: string;
}

@Component({
    template: `
        <div class="card">
            <p-table [columns]="cols" [value]="cars" [scrollable]="true" scrollHeight="400px" [virtualScroll]="true" [virtualScrollItemSize]="46">
                <ng-template #header let-columns>
                    <tr>
                        <th *ngFor="let col of columns" style="width: 20%;">
                            {{ col.header }}
                        </th>
                    </tr>
                </ng-template>
                <ng-template #body let-rowData let-rowIndex="rowIndex" let-columns="columns">
                    <tr style="height:46px">
                        <td *ngFor="let col of columns">
                            {{ rowData[col.field] }}
                        </td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [TableModule],
    providers: [CarService]
})
export class TableVirtualscrollDemo implements OnInit {
    private carService = inject(CarService);
    cars!: Car[];
    virtualCars!: Car[];
    cols!: Column[];

    ngOnInit() {
        this.cols = [
            { field: 'id', header: 'Id' },
            { field: 'vin', header: 'Vin' },
            { field: 'year', header: 'Year' },
            { field: 'brand', header: 'Brand' },
            { field: 'color', header: 'Color' }
        ];
        this.cars = Array.from({ length: 10000 }).map((_, i) => this.carService.generateCar(i + 1));
        this.virtualCars = Array.from({ length: 10000 });
    }
}

virtualscrolllazy-doc

VirtualScroller는 대용량 데이터를 효율적으로 처리하기 위한 성능 접근 방식이에요. virtualScroll 속성을 true로 설정하고 픽셀 단위의 virtualScrollItemSize를 제공하기만 하면 이 기능을 활성화할 수 있어요. 또한 body 템플릿 안의 tr 요소에도 같은 virtualScrollItemSize 값을 사용하는 것이 권장돼요.

import { Component, OnInit, inject } from '@angular/core';
import { SkeletonModule } from 'primeng/skeleton';
import { TableModule } from 'primeng/table';
import { CarService } from '@/service/carservice';
import { TableLazyLoadEvent } from 'primeng/api';
import { Car } from '@/domain/car';

interface Column {
    field: string;
    header: string;
}

@Component({
    template: `
        <div class="card">
            <p-table [columns]="cols" [value]="virtualCars" [scrollable]="true" scrollHeight="400px" [rows]="100" [virtualScroll]="true" [virtualScrollItemSize]="46" [lazy]="true" (onLazyLoad)="loadCarsLazy($event)">
                <ng-template #header let-columns>
                    <tr>
                        <th *ngFor="let col of columns" style="width: 20%;">
                            {{ col.header }}
                        </th>
                    </tr>
                </ng-template>
                <ng-template #body let-rowData let-columns="columns">
                    <tr style="height:46px">
                        <td *ngFor="let col of columns">
                            {{ rowData[col.field] }}
                        </td>
                    </tr>
                </ng-template>
                <ng-template #loadingbody let-columns="columns">
                    <tr style="height:46px">
                        <td *ngFor="let col of columns; let even = even">
                            <p-skeleton [ngStyle]="{ width: even ? (col.field === 'year' ? '30%' : '40%') : '60%' }" />
                        </td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [SkeletonModule, TableModule],
    providers: [CarService]
})
export class TableVirtualscrolllazyDemo implements OnInit {
    private carService = inject(CarService);
    cars!: Car[];
    virtualCars!: Car[];
    cols!: Column[];

    ngOnInit() {
        this.cols = [
            { field: 'id', header: 'Id' },
            { field: 'vin', header: 'Vin' },
            { field: 'year', header: 'Year' },
            { field: 'brand', header: 'Brand' },
            { field: 'color', header: 'Color' }
        ];
        this.cars = Array.from({ length: 10000 }).map((_, i) => this.carService.generateCar(i + 1));
        this.virtualCars = Array.from({ length: 10000 });
    }

    loadCarsLazy(event: TableLazyLoadEvent) {
        //simulate remote connection with a timeout
        setTimeout(
            () => {
                //load data of required page
                let loadedCars = this.cars.slice(event.first, event.first + event.rows);
        
                //populate page of virtual cars
                Array.prototype.splice.apply(this.virtualCars, [...[event.first, event.rows], ...loadedCars]);
        
                //trigger change detection
                event.forceUpdate();
            },
            Math.random() * 1000 + 250
        );
    }
}

Table

Table은 데이터를 표 형식으로 표시해요.

Props

Name Type Default Description
dt InputSignal undefined 컴포넌트의 스코프 디자인 토큰을 정의해요.
unstyled InputSignal undefined 컴포넌트를 스타일 없이 렌더링할지 여부를 나타내요.
pt InputSignal undefined 컴포넌트 내부의 DOM 요소에 속성을 전달하는 데 사용돼요.
ptOptions InputSignal undefined 컴포넌트의 passthrough(pt) 옵션을 구성하는 데 사용돼요.
frozenColumns any[] - 고정된 동적 컬럼을 나타내는 객체 배열이에요.
frozenValue any[] - 고정된 상태로 표시할 객체 배열이에요.
styleClass string - 컴포넌트의 스타일 클래스예요. (지원 중단됨)
tableStyle { [klass: string]: any } - 테이블의 인라인 스타일이에요.
tableStyleClass string - 테이블의 스타일 클래스예요.
paginator boolean false true로 지정하면 페이지네이션이 활성화돼요.
pageLinks number 5 페이지네이터에 표시할 페이지 링크 수예요.
rowsPerPageOptions any[] - 페이지네이터의 페이지당 행 드롭다운 안에 표시할 정수/객체 값 배열이에요.
alwaysShowPaginator boolean true 페이지가 하나뿐인 경우에도 표시할지 여부예요.
paginatorPosition "top" | "bottom" | "both" bottom 페이지네이터의 위치예요. 옵션은 "top", "bottom" 또는 "both"예요.
paginatorStyleClass string - 페이지네이터의 커스텀 스타일 클래스예요.
paginatorDropdownAppendTo any - 페이지네이터 드롭다운 오버레이를 붙일 대상 요소예요. 유효한 값은 "body" 또는 다른 요소의 지역 ng-template 변수예요 (참고: 템플릿 변수에는 대괄호 바인딩을 사용하세요. 예를 들어 #mydiv를 변수 이름으로 가진 div 요소라면 [appendTo]="mydiv"처럼 사용해요).
paginatorDropdownScrollHeight string 200px 페이지네이터 드롭다운 뷰포트의 높이(픽셀)예요. 목록 높이가 이 값을 초과하면 스크롤바가 표시돼요.
currentPageReportTemplate string {currentPage} of {totalPages} 현재 페이지 리포트 요소의 템플릿이에요. 사용할 수 있는 플레이스홀더는 {currentPage},{totalPages},{rows},{first},{last}와 {totalRecords}예요.
showCurrentPageReport boolean false 현재 페이지 리포트를 표시할지 여부예요.
showJumpToPageDropdown boolean false 원하는 페이지로 이동할 수 있는 드롭다운을 표시할지 여부예요.
showJumpToPageInput boolean false 원하는 페이지로 이동할 수 있는 입력 필드를 표시할지 여부예요.
showFirstLastIcon boolean true 활성화하면 첫 페이지와 마지막 페이지로 이동하는 아이콘이 페이지네이터에 표시돼요.
showPageLinks boolean true 페이지 링크를 표시할지 여부예요.
defaultSortOrder number 1 정렬되지 않은 컬럼이 사용자 상호작용으로 정렬될 때 사용할 정렬 순서예요.
sortMode "multiple" | "single" single 정렬이 단일 컬럼에서 동작할지 여러 컬럼에서 동작할지 정의해요.
resetPageOnSort boolean true true이면 정렬 후 페이지네이터를 첫 페이지로 초기화해요. sortMode가 single로 설정된 경우에만 사용할 수 있어요.
selectionMode "multiple" | "single" - 선택 모드를 지정해요. 유효한 값은 "single"과 "multiple"이에요.
selectionPageOnly boolean false 페이지네이터와 체크박스 선택 모드와 함께 활성화하면, 헤더의 전체 선택 체크박스가 현재 페이지의 모든 행을 선택해요.
contextMenuSelection any - 컨텍스트 메뉴로 선택된 행이에요.
contextMenuSelectionMode string separate 컨텍스트 메뉴 선택의 동작 방식을 정의해요. "separate" 모드에서는 컨텍스트 메뉴가 contextMenuSelection 속성을 업데이트하고, joint 모드에서는 대신 selection 속성이 사용되기 때문에 행 선택이 활성화된 경우 행 선택과 컨텍스트 메뉴 선택이 같은 속성을 사용해요.
dataKey string - 데이터에서 레코드를 고유하게 식별하는 속성이에요.
metaKeySelection boolean false 선택 시 metaKey를 고려할지 정의해요. 터치 지원 기기에서는 metaKeySelection이 자동으로 꺼져요.
rowSelectable (row: { data: any; index: number }) => boolean - 행을 선택할 수 있는지 정의해요.
rowTrackBy Function ... ngForTrackBy에 위임해 DOM 작업을 최적화하는 함수예요. 기본 알고리즘은 객체 동일성을 검사해요.
lazy boolean false 데이터를 지연(lazy) 방식으로 로드하고 상호작용할지 정의해요.
lazyLoadOnInit boolean true 초기화 시 지연 로딩을 호출할지 여부예요.
compareSelectionBy "equals" | "deepEquals" deepEquals 행이 선택되었는지 판단하는 알고리즘이에요. 유효한 값은 참조로 비교하는 "equals"와 모든 필드를 비교하는 "deepEquals"예요.
csvSeparator string , csv 구분자로 사용할 문자예요.
exportFilename string download 내보낼 파일의 이름이에요.
filters { [s: string]: FilterMetadata | FilterMetadata[] } {} 외부 필터를 제공하는 FilterMetadata 객체 배열이에요.
globalFilterFields string[] - 전역 필터링에서 사용할 문자열 필드 배열이에요.
filterDelay number 300 데이터를 필터링하기 전의 지연 시간(밀리초)이에요.
filterLocale string - 필터링에서 사용할 로케일이에요. 기본 로케일은 호스트 환경의 현재 로케일이에요.
expandedRowKeys { [s: string]: boolean } {} 펼쳐진 행을 담아두는 Map 인스턴스예요. 맵의 키는 행의 데이터 키예요.
editingRowKeys { [s: string]: boolean } {} 편집 중인 행을 담아두는 Map 인스턴스예요. 맵의 키는 행의 데이터 키예요.
rowExpandMode "multiple" | "single" multiple 여러 행을 언제든 펼칠 수 있는지 여부예요. 유효한 값은 "multiple"과 "single"이에요.
scrollable boolean false 스크롤 가능한 테이블을 활성화해요.
rowGroupMode "subheader" | "rowspan" - 행 그룹화의 유형이에요. 유효한 값은 "subheader"와 "rowspan"이에요.
scrollHeight string - 스크롤 뷰포트의 높이예요. 고정 픽셀 값이나 동적 크기를 위한 "flex" 키워드를 사용할 수 있어요.
virtualScroll boolean false 스크롤 중에 데이터를 필요할 때 로드할지 여부예요.
virtualScrollItemSize number - 가상 스크롤 계산에 사용할 행의 높이예요.
virtualScrollOptions ScrollerOptions - scroller 기능을 사용할지 여부예요. scroller 컴포넌트의 속성을 객체 형태로 담아 사용할 수 있어요.
virtualScrollDelay number 250 스크롤 중 지연 로딩을 늦추는 임계값(밀리초)이에요.
frozenWidth string - 고정 컬럼 컨테이너의 너비예요.
contextMenu any - ContextMenu의 지역 ng-template 변수예요.
resizableColumns boolean false 활성화하면 드래그 앤 드롭으로 컬럼 크기를 조절할 수 있어요.
columnResizeMode string fit 컬럼 크기 조절 시 테이블 전체 너비가 변경될지 정의해요. 유효한 값은 "fit"과 "expand"예요.
reorderableColumns boolean false 활성화하면 드래그 앤 드롭으로 컬럼 순서를 변경할 수 있어요.
loading boolean false 데이터 로드가 진행 중임을 나타내는 로더를 표시해요.
loadingIcon string - 데이터 로드가 진행 중임을 나타낼 때 표시할 아이콘이에요.
showLoader boolean true loading 속성이 true일 때 로딩 마스크를 표시할지 여부예요.
rowHover boolean false selectionMode 없이도 행에 호버 효과를 추가해요. rowHover가 동작하려면 호버할 수 있는 tr 요소에 "p-selectable-row" 클래스가 있어야 한다는 점에 유의하세요.
customSort boolean false 기본 정렬을 사용할지 sortFunction을 이용한 커스텀 정렬을 사용할지 여부예요.
showInitialSortBadge boolean true 초기 정렬 배지를 사용할지 여부예요.
exportFunction Function - 내보내기 함수예요.
exportHeader string - CSV로 내보낼 컬럼의 커스텀 내보내기 헤더예요.
stateKey string - 상태 저장에 사용될 상태 유지 테이블의 고유 식별자예요.
stateStorage "session" | "local" session 상태 유지 테이블이 상태를 보관할 위치를 정의해요. 유효한 값은 sessionStorage를 위한 "session"과 localStorage를 위한 "local"이에요.
editMode "row" | "cell" cell 편집 모드를 정의해요. 유효한 값은 "cell"과 "row"예요.
groupRowsBy any - 행 그룹화에 사용할 필드 이름이에요.
size "small" | "large" - 테이블의 크기를 정의해요.
showGridlines boolean false 셀 사이에 그리드 라인을 표시할지 여부예요.
stripedRows boolean false 행을 교대로 다른 색상으로 표시할지 여부예요.
groupRowsByOrder number 1 기본 행 그룹화가 활성화되었을 때 정렬할 순서예요.
responsiveLayout string scroll 반응형 모드를 정의해요. 유효한 옵션은 "stack"과 "scroll"이에요. (지원 중단됨)
breakpoint string 960px stack 반응형 레이아웃을 사용할 때 최대 너비 경계를 정의하는 브레이크포인트예요.
paginatorLocale string - 페이지네이터 포맷팅에 사용할 로케일이에요.
value RowData[] - 표시할 객체 배열이에요.
columns any[] - 동적 컬럼을 나타내는 객체 배열이에요.
first number - 표시할 첫 번째 행의 인덱스예요.
rows number - 페이지당 표시할 행 수예요.
totalRecords number 0 전체 레코드 수예요. 정의하지 않으면 value의 길이가 기본값으로 사용돼요.
sortField string - 기본적으로 데이터를 정렬할 필드의 이름이에요.
sortOrder number - 기본 정렬이 활성화되었을 때 정렬할 순서예요.
multiSortMeta SortMeta[] - 다중 정렬 모드에서 기본으로 데이터를 정렬하는 SortMeta 객체 배열이에요.
selection any - single 모드에서는 선택된 행, multiple 모드에서는 값 배열이에요.
selectAll boolean - 모든 데이터가 선택되었는지 여부예요.

이벤트 방출

이름 파라미터 설명
contextMenuSelectionChange value: any 컨텍스트 메뉴 선택이 변경될 때 호출되는 콜백이에요.
selectAllChange event: TableSelectAllChangeEvent 모든 항목이 선택되거나 선택 해제될 때 발생해요.
selectionChange value: any 선택이 변경될 때 호출되는 콜백이에요.
onRowSelect event: TableRowSelectEvent<RowData 행이 선택될 때 호출되는 콜백이에요.
onRowUnselect event: TableRowUnSelectEvent<RowData 행이 선택 해제될 때 호출되는 콜백이에요.
onPage event: TablePageEvent 페이지네이션이 발생할 때 호출되는 콜백이에요.
onSort value: any 컬럼이 정렬될 때 호출되는 콜백이에요.
onFilter event: TableFilterEvent 데이터가 필터링될 때 호출되는 콜백이에요.
onLazyLoad event: TableLazyLoadEvent 레이지 모드에서 페이징, 정렬 또는 필터링이 발생할 때 호출되는 콜백이에요.
onRowExpand event: TableRowExpandEvent<RowData 행이 펼쳐질 때 호출되는 콜백이에요.
onRowCollapse event: TableRowCollapseEvent 행이 접힐 때 호출되는 콜백이에요.
onContextMenuSelect event: TableContextMenuSelectEvent<RowData 행을 오른쪽 클릭으로 선택할 때 호출되는 콜백이에요.
onColResize event: TableColResizeEvent 컬럼 크기가 조정될 때 호출되는 콜백이에요.
onColReorder event: TableColumnReorderEvent 컬럼 순서가 변경될 때 호출되는 콜백이에요.
onRowReorder event: TableRowReorderEvent 행 순서가 변경될 때 호출되는 콜백이에요.
onEditInit event: TableEditInitEvent 셀이 편집 모드로 전환될 때 호출되는 콜백이에요.
onEditComplete event: TableEditCompleteEvent 셀 편집이 완료될 때 호출되는 콜백이에요.
onEditCancel event: TableEditCancelEvent escape 키로 셀 편집이 취소될 때 호출되는 콜백이에요.
onHeaderCheckboxToggle event: TableHeaderCheckboxToggleEvent 헤더 체크박스 상태가 변경될 때 호출되는 콜백이에요.
sortFunction value: any 커스텀 정렬을 구현하기 위한 함수예요. 자세한 내용은 정렬 섹션을 참고하세요.
firstChange value: number 페이지네이션 시 호출되는 콜백이에요.
rowsChange value: number 행 수가 변경될 때 호출되는 콜백이에요.
onStateSave value: TableState 테이블 상태가 저장될 때 호출되는 콜백이에요.
onStateRestore value: TableState 테이블 상태가 복원될 때 호출되는 콜백이에요.

메서드

이름 파라미터 반환 타입 설명
exportCSV options: ExportCSVOptions void 데이터 내보내기 메서드예요.
resetScrollTop void 스크롤을 맨 위로 초기화해요.
scrollToVirtualIndex index: number void 가상 스크롤 사용 시 주어진 인덱스로 스크롤해요.
scrollTo options: any void 주어진 인덱스로 스크롤해요.

Pass Through 옵션

이름 타입 설명
filter PassThroughOption<HTMLDivElement, I> 필터 컨테이너 엘리먼트에 속성을 전달하는 데 사용해요.
pcColumnFilterButton ButtonPassThrough 컬럼 필터 버튼 컴포넌트에 속성을 전달하는 데 사용해요.
filterOverlay PassThroughOption<HTMLDivElement, I> 필터 오버레이 엘리먼트에 속성을 전달하는 데 사용해요.
filterConstraintList PassThroughOption<HTMLUListElement, I> 필터 제약 조건 리스트 엘리먼트에 속성을 전달하는 데 사용해요.
filterConstraint PassThroughOption<HTMLLIElement, I> 필터 제약 조건 엘리먼트에 속성을 전달하는 데 사용해요.
filterConstraintSeparator PassThroughOption<HTMLLIElement, I> 필터 제약 조건 구분자 엘리먼트에 속성을 전달하는 데 사용해요.
emtpyFilterLabel PassThroughOption<HTMLLIElement, I> 빈 필터 라벨 엘리먼트에 속성을 전달하는 데 사용해요.
filterOperator PassThroughOption<HTMLDivElement, I> 필터 연산자 엘리먼트에 속성을 전달하는 데 사용해요.
pcFilterOperatorDropdown SelectPassThrough 필터 연산자 드롭다운 컴포넌트에 속성을 전달하는 데 사용해요.
filterRuleList PassThroughOption<HTMLDivElement, I> 필터 규칙 리스트 엘리먼트에 속성을 전달하는 데 사용해요.
filterRule PassThroughOption<HTMLDivElement, I> 필터 규칙 엘리먼트에 속성을 전달하는 데 사용해요.
pcFilterConstraintDropdown SelectPassThrough 필터 제약 조건 드롭다운 컴포넌트에 속성을 전달하는 데 사용해요.
pcFilterRemoveRuleButton ButtonPassThrough 필터 규칙 제거 버튼 컴포넌트에 속성을 전달하는 데 사용해요.
pcAddRuleButtonLabel ButtonPassThrough 규칙 추가 버튼 라벨에 속성을 전달하는 데 사용해요.
filterButtonBar PassThroughOption<HTMLDivElement, I> 필터 버튼 바 엘리먼트에 속성을 전달하는 데 사용해요.
pcFilterClearButton ButtonPassThrough 필터 지우기 버튼 컴포넌트에 속성을 전달하는 데 사용해요.
pcFilterApplyButton ButtonPassThrough 필터 적용 버튼 컴포넌트에 속성을 전달하는 데 사용해요.
pcFilterInputText InputTextPassThrough 필터 텍스트 입력 컴포넌트에 속성을 전달하는 데 사용해요.
pcFilterInputNumber InputNumberPassThrough 필터 숫자 입력 컴포넌트에 속성을 전달하는 데 사용해요.
pcFilterCheckbox CheckboxPassThrough 필터 체크박스 컴포넌트에 속성을 전달하는 데 사용해요.
pcFilterDatePicker DatePickerPassThrough 필터 데이트피커 컴포넌트에 속성을 전달하는 데 사용해요.
motion MotionOptions 모션 컴포넌트/디렉티브에 옵션을 전달하는 데 사용해요.

테마

CSS 클래스

클래스 설명
p-datatable 루트 엘리먼트의 클래스 이름이에요.
p-datatable-mask 마스크 엘리먼트의 클래스 이름이에요.
p-datatable-loading-icon 로딩 아이콘 엘리먼트의 클래스 이름이에요.
p-datatable-header 헤더 엘리먼트의 클래스 이름이에요.
p-datatable-paginator-[position] 페이지네이터 엘리먼트의 클래스 이름이에요.
p-datatable-table-container 테이블 컨테이너 엘리먼트의 클래스 이름이에요.
p-datatable-table 테이블 엘리먼트의 클래스 이름이에요.
p-datatable-thead thead 엘리먼트의 클래스 이름이에요.
p-datatable-column-resizer 컬럼 리사이저 엘리먼트의 클래스 이름이에요.
p-datatable-column-header-content 컬럼 헤더 콘텐츠 엘리먼트의 클래스 이름이에요.
p-datatable-column-title 컬럼 타이틀 엘리먼트의 클래스 이름이에요.
p-datatable-sort-icon 정렬 아이콘 엘리먼트의 클래스 이름이에요.
p-datatable-sort-badge 정렬 배지 엘리먼트의 클래스 이름이에요.
p-datatable-filter 필터 엘리먼트의 클래스 이름이에요.
p-datatable-filter-element-container 필터 엘리먼트 컨테이너 엘리먼트의 클래스 이름이에요.
p-datatable-column-filter-button 컬럼 필터 버튼 엘리먼트의 클래스 이름이에요.
p-datatable-column-filter-clear-button 컬럼 필터 지우기 버튼 엘리먼트의 클래스 이름이에요.
p-datatable-filter-overlay 필터 오버레이 엘리먼트의 클래스 이름이에요.
p-datatable-filter-constraint-list 필터 제약 조건 리스트 엘리먼트의 클래스 이름이에요.
p-datatable-filter-constraint 필터 제약 조건 엘리먼트의 클래스 이름이에요.
p-datatable-filter-constraint-separator 필터 제약 조건 구분자 엘리먼트의 클래스 이름이에요.
p-datatable-filter-operator 필터 연산자 엘리먼트의 클래스 이름이에요.
p-datatable-filter-operator-dropdown 필터 연산자 드롭다운 엘리먼트의 클래스 이름이에요.
p-datatable-filter-rule-list 필터 규칙 리스트 엘리먼트의 클래스 이름이에요.
p-datatable-filter-rule 필터 규칙 엘리먼트의 클래스 이름이에요.
p-datatable-filter-constraint-dropdown 필터 제약 조건 드롭다운 엘리먼트의 클래스 이름이에요.
p-datatable-filter-remove-rule-button 필터 규칙 제거 버튼 엘리먼트의 클래스 이름이에요.
p-datatable-filter-add-rule-button 필터 규칙 추가 버튼 엘리먼트의 클래스 이름이에요.
p-datatable-filter-buttonbar 필터 버튼 바 엘리먼트의 클래스 이름이에요.
p-datatable-filter-clear-button 필터 지우기 버튼 엘리먼트의 클래스 이름이에요.
p-datatable-filter-apply-button 필터 적용 버튼 엘리먼트의 클래스 이름이에요.
p-datatable-tbody tbody 엘리먼트의 클래스 이름이에요.
p-datatable-row-group-header 행 그룹 헤더 엘리먼트의 클래스 이름이에요.
p-datatable-row-toggle-button 행 토글 버튼 엘리먼트의 클래스 이름이에요.
p-datatable-row-toggle-icon 행 토글 아이콘 엘리먼트의 클래스 이름이에요.
p-datatable-row-expansion 행 확장 엘리먼트의 클래스 이름이에요.
p-datatable-row-group-footer 행 그룹 푸터 엘리먼트의 클래스 이름이에요.
p-datatable-empty-message 빈 메시지 엘리먼트의 클래스 이름이에요.
p-datatable-reorderable-row-handle 행 순서 변경 핸들 엘리먼트의 클래스 이름이에요.
p-datatable-row-editor-init 행 에디터 초기화 엘리먼트의 클래스 이름이에요.
p-datatable-row-editor-save 행 에디터 저장 엘리먼트의 클래스 이름이에요.
p-datatable-row-editor-cancel 행 에디터 취소 엘리먼트의 클래스 이름이에요.
p-datatable-tfoot tfoot 엘리먼트의 클래스 이름이에요.
p-datatable-virtualscroller-spacer 가상 스크롤러 스페이서 엘리먼트의 클래스 이름이에요.
p-datatable-footer 푸터 엘리먼트의 클래스 이름이에요.
p-datatable-column-resize-indicator 컬럼 크기 조정 인디케이터 엘리먼트의 클래스 이름이에요.
p-datatable-row-reorder-indicator-up 행 순서 변경 위쪽 인디케이터 엘리먼트의 클래스 이름이에요.
p-datatable-row-reorder-indicator-down 행 순서 변경 아래쪽 인디케이터 엘리먼트의 클래스 이름이에요.
p-datatable-sortable-column 정렬 가능 컬럼 엘리먼트의 클래스 이름이에요.
p-sortable-column-icon 정렬 가능 컬럼 아이콘 엘리먼트의 클래스 이름이에요.
p-sortable-column-badge 정렬 가능 컬럼 배지 엘리먼트의 클래스 이름이에요.
p-datatable-selectable-row 선택 가능 행 엘리먼트의 클래스 이름이에요.
p-datatable-resizable-column 크기 조정 가능 컬럼 엘리먼트의 클래스 이름이에요.
p-datatable-row-editor-cancel 행 에디터 취소 엘리먼트의 클래스 이름이에요.
p-datatable-frozen-column 고정 컬럼 엘리먼트의 클래스 이름이에요.
p-datatable-contextmenu-row-selected 컨텍스트 메뉴로 선택된 행 엘리먼트의 클래스 이름이에요.

더 알아보기 (Learn more)

이 문서에는 원문에서 추출한 별도의 관련 문서 링크가 없어요.