Search code examples
htmlangularrowprimeng

PrimeNG Table: Programmatically handle row editing (pSaveEditableRow)


I'm using a PrimeNG Table, and I would like to handle saving row editing programmatically in the case that there are any custom validation errors that need to be addressed beforehand in edit mode. Currently, I have added pSaveEditableRow to a button, which on click, ends row editing and saves edits made to the row. I need to override this and do some validation beforehand. How can this be accomplished?

I've looked into the documentation for PrimeNG, and it looks like I may be able to call the 'saveRowEdit' function, but I need to pass rowData and rowElement, both of which come from pEditableRow, and pEditableRow appears to be set to an object with properties needed for the table.

References: https://github.com/primefaces/primeng/blob/b3e7b3582f98936e0cddcafc921c61a9eabf9bcd/src/app/components/table/table.ts#L1883

https://github.com/primefaces/primeng/blob/b3e7b3582f98936e0cddcafc921c61a9eabf9bcd/src/app/components/table/table.ts#L3807


Solution

  • For those who want to end edit mode on a row manually, I've found a solution:

    1. Remove pSaveEditableRow from your button tag (if you have added it). As the documentation states, pSaveEditableRow simply switches the row back to view mode.

    2. Add #htmlTableRowElement to your <tr> tag: <tr [pEditableRow]="rowData" #htmlTableRowElement>...</tr>

    3. Pass rowData and htmlTableRowElement in to the (click) function on the button tag.

    4. Add import { Table } from 'primeng/table' to your component.

    5. Add @ViewChild('dt', { static: false }) table: Table to your component.

    6. Add #dt to your <p-table>: <p-table #dt>...</p-table>

    7. You can now call this.table.saveRowEdit(rowData, htmlTableRowElement) in your function which is invoked on button click. This will end edit mode for the row and put it into view mode. rowData is a type of any (an object containing your row data), and htmlTableRowElement is pretty self-explanatory.

    Hope this helps!