javascripthtmljqueryangularjsangular

Angular way to stop negative values from being entered in input type number (on copy-paste & increase, decrease) also


my requirement is in an angular project i'm taking number input in a form like this

<input type="number" #input class="form-control" [(ngModel)]="dataItem.quantity"

i should not allow user to enter negative values even from copy-paste or through increase / decrease button of input type number or thought keyboard.

how can we acheive this, i have seen some directives, there they are taking input as 'text', my case is it should be "input type number" only.

It should allow decimals also.

Please Help me.


Solution

  • You can do like below

    HTML:

    <input type="number" min="0" (input)="checkValue($event)">
    

    TS:

    checkValue(event) {
      if (event.target.value < 0) {
        event.target.value = 0;
      }
    }
    

    You can use (keyup) too

    Update:

    In the Angular way, you can create a pipe. Working stackblitz

    In the HTML:

    <input type="number" min="0" [ngModel]="testValue | nonegativevalue" (ngModelChange)="testValue=$event">
    

    nonegativevaluepipe

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({name: 'nonegativevalue'})
    export class NoNegativeValue implements PipeTransform {
      transform(value: number): number {
        if(value < 0) {
          value = 0;
          return value;
        }
        return value;
      }
    }
    

    If you use reactive form, then check this stackblitz