3

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.

Shaik Habeeb
  • 205
  • 1
  • 5
  • 15

2 Answers2

3

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

Sivakumar Tadisetti
  • 4,865
  • 7
  • 34
  • 56
2

Try this..

<input type="number" min="0" #input class="form-control" [(ngModel)]="dataItem.quantity" 
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">
aks44
  • 422
  • 3
  • 12