How to limit an input of type Number to only 3 characters by Angular 7?

Asked

Viewed 746 times

2

I have a problem with a variable of type integer, because maxlength="" only works with string and need to bar, but is of type Number. I think you need javascript, if anyone knows the solution would appreciate.

1 I have a problem with a variable of type integer, because maxlength="" only works with string and need to bar, but is of type Number. I think you need javascript, if anyone knows the solution would appreciate.

Update: I’m already using max="999" and min="0", but not working.

I found the following solution if it was with javasctipt;

function somenteNumeros(e) {
    var charCode = e.charCode ? e.charCode : e.keyCode;
    // charCode 8 = backspace   
    // charCode 9 = tab
   if (charCode != 8 && charCode != 9) {
       // charCode 48 equivale a 0   
       // charCode 57 equivale a 9
       var max = 3;
       var num = document.getElementById('num');           

       if ((charCode < 48 || charCode > 57)||(num.value.length >= max)) {
          return false;
       }

    }
}

HTML

<input id="num" placeholder="Digite o numero" type="number" onkeypress="return somenteNumeros(event)" required>

But I’m using Angular and I need a solution that the code snippet was in typescript!

1 answer

3


Is developing with Angular should already know how to transpose a code Vanila for Typescript, I made an example here for you that can be tested in stackblitz:

TS:

somenteNumeros(e: any) {
  let charCode = e.charCode ? e.charCode : e.keyCode;
  // charCode 8 = backspace   
  // charCode 9 = tab

  if (charCode != 8 && charCode != 9) {
    // charCode 48 equivale a 0   
    // charCode 57 equivale a 9
    let max = 3;    

    if ((charCode < 48 || charCode > 57)||(e.target.value.length >= max)) return false;
  }
}

HTML

<input id="num"  placeholder="Digite o numero" type="number" (keypress)="somenteNumeros($event)" required>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.