PrimeNG Turbotable expand by default
After hitting many solution i tried and found easiest way to resolve
<p-table [columns]="cols" [value]="cars" dataKey="vin" [expandedRowKeys]="expandedRows">
Replace datakey value to your unique id key from list of objects fetched from service or http calls.
<p-table [columns]="cols" [value]="repaymentsList" dataKey="id" expandableRows="true" rowExpandMode="single" [responsive]="true">
Update: For Version >7.x
Setting value to 1 won't work on version 7+ use boolean(true/false)
const thisRef = this;
this.cars.forEach(function(car) {
thisRef.expandedRows[car.vin] = true;
});
Working StackBlitz
For Version <7.x
I tried using expandedRowKeys attribute
Yes you're right. So add [expandedRowKeys]="expandedRows">
to p-table
element :
<p-table [columns]="cols" [value]="cars" dataKey="vin" [expandedRowKeys]="expandedRows">
and then, you just need to fill expandedRows
object with vin
values of the rows you want to expand (because dataKey
is vin
).
Because you want all rows to be expanded, you can fill it like that :
const thisRef = this;
this.cars.forEach(function(car) {
thisRef.expandedRows[car.vin] = 1;
});
in order to have something like
expandedRows = {"dsad231ff": 1, "gwregre345": 1, ...}
See working Plunker
In the accepted answer, the expandedRows mapping to the turbo table expandedRowKeys is one way i.e. it can set the state of rows at the time of loading only. If someone want to collapse or expand it after the table is loaded, you can directly edit the 'expandedRowKeys' variable by passing the table reference from the html.
Define Your table with a reference variable #dt
<p-table #dt [columns]="cols" [value]="cars" dataKey="vin">
Edit your table body like this to get a on click function trigger
<ng-template pTemplate="body" let-rowData let-expanded="expanded" let-columns="columns">
<tr>
<td>
<a href="#" [pRowToggler]="rowData">
<i [ngClass]="expanded ? 'fa fa-fw fa-chevron-circle-down' : 'fa fa-fw fa-chevron-circle-right'"></i>
</a>
</td>
<td *ngFor="let col of columns">
<a >
<span (click)="onItemClick(rowData, dt)">
{{rowData[col.field]}}
</span>
</a>
</td>
</tr>
</ng-template>
in your TS file add the function as
onItemClick(rowData:any, dt:any) {
if(dt.expandedRowKeys[rowData._id]){
dt.expandedRowKeys[rowData._id] = 0;
}
else {
dt.expandedRowKeys[rowData._id] = 1;
}
}
This approach gives you more freedom in changing state of table on a trigger of event from outside of table and expanding or collapsing multiple rows at once.