Skip to content
Advertisement

Angular 2/4 need a Typescript regex to only allow numbers to be entered into input textbox

In my Angular 4 application I have this input box in which I ONLY want numbers… 0-9 to be entered.. otherwise I want it to clear out onkeyup

HTML

JavaScript

Above works to call this function in the component but it is not working to prevent letters.

JavaScript
  1. Is .value the wrong approach?
  2. Should I be using event preventdefault?

The console log for ‘y’ shows correctly.

What do I need to do?

Advertisement

Answer

Since you are using ReactiveForm, you should understand that FormConrtol’s value only has a getter.

If you want to change formControl’s value, use patchValue or setValue.

JavaScript

Refer demo.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement