0
votes

My requirement is as below,

I have a text field, which should accept only numbers. When I enter any other characters, it should not be allowed (that is it should not be displayed in the text box). I cannot use input type number as it allows "-", "+" and e.

I tried using many events like, ngModelChange, keypress, keydown, input, change. But none of them worked as expected.

I have recreated my problem in below link,

https://stackblitz.com/edit/angular-en6w18

Any help appreciated. Thanks.

1
Why keydown didn't work? - Raeef Refai
When i use keydown, the last character i type is still displayed and not removed. I have no idea why that happens. You can check the behaviour in the link I have shared. - Santhosh mp
Thanks, It works. - Santhosh mp

1 Answers

2
votes

You should call preventDefault if the entered char is not a number

here is how it will work:

https://stackblitz.com/edit/angular-tkaeug

Note: don't forget to allow alt, ctrl, command, backspace.... etc.