Mathijs Segers
Mathijs Segers

Reputation: 6238

Angular2 input type number, no decimal value

I've been wondering, what is the proper approach in preventing decimals from being entered in number inputs for angular2.

Is there a certain event or constraint I can add? When I for example just use pattern or such it will only invalidate the field but still allow typing.

What would be the proper way to prevent this, just ye olde, keyUp event and checking keystroke?

Since according to comments, asking for patterns or w/e is wrong, here is what I now implemented and works like a charm

<input (keypress)="preventInput($event)" type="number" step="1">

with preventInput as:

private preventInput(event) {
  console.log(event.keyCode);
  switch(event.keyCode) {
    case 101: //e
    case 46: //.
      event.preventDefault();
      break;
  }
}

this won't however prevent input of . by pasting but is good enough for us.

Upvotes: 1

Views: 4785

Answers (2)

nikk wong
nikk wong

Reputation: 8670

In angular 2 this is very similar to angular1. The takeaway is that it is preferable to keep the logic running within angular because you can trigger/react to other angular events based on the current event, if you ever needed to do so, or if the logic in this class ever was to grow.

The syntax is different but the logic is very much the same—creating a directive that listens to keystrokes.

@Directive({
   selector: 'prevent-input',
   template: `<input type="text" (keypress)="preventKeyStrokes($event)">`
})

export class PreventInput {
   constructor() {}
   preventKeyStrokes(event) {
          event.preventDefault();    
          event = event || window.event;
          var key = event.keyCode || event.which;
          key = String.fromCharCode(key);
          var strToTest = '.';
          if (/* some regex with '.' */.test(key)) {
              return false;
          }
    } 
}

$event is a DOM Keyboard event. Let me know if I can be of any more help.

Upvotes: 1

nikk wong
nikk wong

Reputation: 8670

I've usually seen it done via custom directives. This is preferable to vanilla JS because you can use the scope object to listen into the key events if you want to bind some other angular logic into the event now or in the future.

angular.directive('preventSomeKeystrokes', function () {
    link(scope, elem, attrs) {
       elem.on('keydown', function (event) {
          event.preventDefault();    
          event = event || window.event;
          // maybe prevent certain keys dynamically with $scope?
          // or see how often your users are typing in '.'s with angular.$log().
          var key = _event.keyCode || _event.which;
          key = String.fromCharCode(key);
          var strToTest = '.';
          if (/* some regex with '.' */.test(key)) {
              return false;
          }
      }
});

Upvotes: 1

Related Questions