Why does the primeng p-table element throw an error but still update the record when editing a row?

146 Views Asked by At

I'm referring to the following primeng p-table example:

url: https://primeng.org/table#Edit (Click on the stackblitz icon in the top right corner as highlighted in blue below)

enter image description here

As you can see if I update the price to an invalid value & then click the check mark,

the toast error message displays, but it still updates the record!

enter image description here

How can I prevent this from happening?

Thanks very much.

1

There are 1 best solutions below

2
cbarringer On

This is a result of typescript not doing runtime type checking. The ngModel for price is binded to product.price. As the user inputs, for example, a string into the price field, the ngModel updates, even though the string type is not compatible with the number type. Typescript does not care, as it does not check types at runtime. In the method onRowEditSave(), the program checks that product.price is greater than zero. This is not true when product.price is a string. Therefore, the statement evaluates to false, and the program throws the error 'Invalid Price.'

To fix this, you could use a p-inputNumber instead of using a regular input with the pInputText directive. The inputNumber component does not allow the user to input normal text, just numbers.