1
votes

I'm trying to code a way for the end-user to click an "Add New Row" button and have a blank row appear inline as the first row of the p-datatable. Currently when I add the new item to the array behind the scenes, that row appears in a seemingly random spot in the table.

I think the solution must involve being able to sort by a hidden column behind the scenes, no matter what the user-selected sort order is on the table. For example, user is currently sorting by Last Name column ascending, so I order first by an invisible Sorter column descending, then by Last Name ascending. Every record in the table would have a value of 0 for sorter, except for the newly added row, which is given a value of 1.

How, then, do I override sorting for p-datatable in order to make my new rows always appear at the top of the table no matter how the end-user has sorted the table using the GUI? Right now, when the user clicks a column to sort by, it removes my sorting behind the scenes.

Thanks!

1

1 Answers

0
votes

First you might want to create a row dummy (I create it dynamically, because I get the name of the columns from the server). According to primeng docs when adding/removing rows you should always create a new array reference instead of manipulating an existing array as Angular does not trigger setters if the reference does not change. The new rows will then appear at the top until user clicks the column header to sort the rows.

Here is the code I use for adding the row to the beginning of the table:

buildNewRowDummy(): string[] {
    const newRowDummy = [];
    for (let col = 0; col < this.cols.length; col++) {
      const columnName = this.cols[col];
      newRowDummy[columnName] = '';
    }

    return newRowDummy;
  }

addRow() {
  this.rows = [ this.buildNewRowDummy(), ...this.rows ];
}