Overview
PrimeNG’s p-table supports row selection through the selectionMode attribute. The selected rows are bound to a component property. By initializing this property you can make rows checked automatically.
Use selectionMode and selection binding
Add selectionMode="multiple" to the table and bind the selection property to a local array.
<p-table [value]="products" selectionMode="multiple" [(selection)]="selectedProducts">
<ng-template pTemplate="header">
<tr>
<th pSelectableRow></th>
<th>Name</th>
<th>Price</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-product let-rowIndex="rowIndex">
<tr>
<td pSelectableRow></td>
<td>{{product.name}}</td>
<td>{{product.price}}</td>
</tr>
</ng-template>
</p-table>
Pre-select rows in component.ts
Populate the selectedProducts array with the row objects you want checked. The comparison uses object identity, so the same instance must be used.
export class ProductTableComponent {
products = [
{ id: 1, name: 'Apple', price: 1.2 },
{ id: 2, name: 'Banana', price: 0.8 },
{ id: 3, name: 'Cherry', price: 2.5 }
];
selectedProducts = [];
ngOnInit() {
// Pre‑select Apple and Cherry
this.selectedProducts = this.products.filter(p => p.id === 1 || p.id === 3);
}
}
Update UI after data load
If the table data comes asynchronously, set the selection inside the subscription or after the data is assigned.
this.productService.getAll().subscribe(data => {
this.products = data;
this.selectedProducts = this.products.filter(p => p.id === 2); // select Banana
});
Common pitfalls
1. Using a different object instance for selection will not work. 2. Changing the selection array reference without re‑assigning it may not trigger change detection. 3. Remember to include pSelectableRow in the header and body templates.
Takeaway: Default selection in PrimeNG tables is achieved by binding the selection array to the table and initializing it with desired rows.
People also ask
Can I select rows after the table has rendered?
Yes, push the row objects into the selection array or assign a new array; PrimeNG will update the checkboxes.
How to deselect all rows programmatically?
Set the selection array to an empty array: this.selectedProducts = [];
Inspired by a public discussion on Stack Overflow. This article is an original explanation for learners.