0

html file

<input type="text" size="10" onkeypress="return numbersOnly($event)">

component.ts

public numbersOnly(event) {
  return event.charCode >= 48 && event.charCode <= 57;
}

I don't why my code not work! Please help me. Thank you very much.

nguyenhuyenag
  • 313
  • 5
  • 13

4 Answers4

2

use the Angular DOM event emitter keypress

(keypress)="eventHandler($event)"

Is the standard event handler. You can implement a method this way.

It's also useful to note that all the HTML5 standard DOM event emitters work this way in Angular, onthisevent -> thisevent e.g. onkeypress -> (keypress), onblur -> (blur) etc.

Z. Bagley
  • 8,942
  • 1
  • 40
  • 52
1

Why cant you just change the type as number?

<input type="number" size="10" >
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

what is the point of using type="text" if you want to type number.If you only need to type number use type="number" here you don't want to write any function to restrict keys.use as below

<input type="number" size="10" >
Thusila Bandara
  • 285
  • 4
  • 22
0
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
</input>

or

as Sajeetharan mentioned, HTML5 now also support input with type number

Asura
  • 859
  • 5
  • 15