How to add a new row inline to PrimeNG p-table

I am a big fan and user of PrimeNG’s Angular component for grids and tables. Out of the box the component has the capability to perform inline editing and deleting with little custom code utilizing three builtin PrimeNG directives:

  • pInitEditableRow
  • pSaveEditableRow
  • pCancelEditableRow

However, there is no builtin mechanism for adding a new row inline and the standard approach is to have a button somewhere on a page that opens a modal dialog window that adds a new row as shown below.

This blog implements a solution where new row is inserted inline into the grid/able dynamically, thereby, eliminating the need fora modal dialog window.

The solution employs an Angular directive with a decorator that declares a DOM click event to listen for, and provides a handler method to run when that event occurs.

The directive has two @Input values: one that references the PrimeNG table and the other is the new row to be added to the table. In the body of the onClick method, the new row is added to the table’s rows and the new row is then put in edit mode. Finally, the click event is prevented from bubbling up.

In the component where the PrimeNG p-table is used, a button is added at the bottom of the p-table. The button has a pAddRow directive, ‘table’ and ‘newRow’ @Input are assigned values.

When the ‘Add’ button is clicked, a new row is added at the bottom of the table as shown below.

See live demo

Dan