Using checkbox selection and row selection together in PrimeNg table

Viewed 7072

I am using PrimeNg table component and needs to implement row selection. I have the following code:

    <p-table
        [value]="data"
        [columns]="columns"
        [(selection)]="selectedItems"
        selectionMode="multiple">
    <ng-template pTemplate="header">
        <tr>
            <th>
                <p-tableHeaderCheckbox style="margin-left: 5px;"></p-tableHeaderCheckbox>
            </th>
            <th>Header 1</th>
            <th>Header 2</th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-row>
        <tr [pSelectableRow]="row">
            <td>
                <p-tableCheckbox [value]="row"></p-tableCheckbox>
            </td>
            <td>Value 1</td>
            <td>Value 2</td>
        </tr>
    </ng-template>
</p-table>

Basically, I am using the Checkbox selection and multiple selection without metakey as given in the documentation here. Now when I click on the row, it is selecting and the checkbox is also checked. But when I click on the checkbox, it is not getting selected. If I click on the Select All, then also it is selecting all the rows. When I checked using Developer Tools, it is not making the aria-checked to true even though the click is detected.

Any workaround for fixing this issue?

5 Answers

@Arun's answer is correct. I'm just adding some formatting if someone also stumbles on this problem and is short of time ;) :

<ng-template pTemplate="body" let-data>
    <tr [pSelectableRow]="data">
       <td>
          <p-tableCheckbox [pSelectableRow]="data" [value]="data"></p-tableCheckbox>
       </td>
    </tr>
</ng-template>

It also works well without providing [index] to the tableCheckbox.

Yes R.Richards is right adding dataKey should resolve the problem. But still without dataKey just add this <p-tableCheckbox [value]="row" [pSelectableRow]="row"></p-tableCheckbox>with your row checkbox. This should work as I remember I had done something like this earlier with my code:)

I've observed that when you add pSelectableRow to both tr and p-tableCheckbox, like in the @Arun's answer, selection is triggered 3 times. First, it adds selection to selections array, second it removes it and finally in the 3rd time adds again. So if you act on selection change it can be a problem. I cannot figure out the exact reason though, strange behaviour.

Also, please note that this particular use case is not officially supported.

I had the same issue using p-tableCheckbox and pSelectableRow. Removing the selectionMode binding solved it. As in this example.

You can stop the checkboxes behavior using simple css - pointer-events: none. Your click should still affect the row, but not propagate down to the checkbox

Related