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
  • 303
  • 5
  • 12

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,432
  • 1
  • 37
  • 51
1

Why cant you just change the type as number?

<input type="number" size="10" >
Sajeetharan
  • 203,447
  • 57
  • 330
  • 376
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
  • 284
  • 3
  • 21
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
  • 829
  • 5
  • 15