2

I have a shop component and I need to disallow people to pick negative numbers in my input.

For example, if user will type -3 in my input, the input value will immadiately change to 0.

How I can control my angular 2 input OnChange value to set it back to 0 it the value is negative?

Tried to use (ngModelChange)="myMethod($event)" and set the parameter to 0 if it's negative, but didn't work.

Tordek
  • 10,628
  • 3
  • 36
  • 67
TheUnreal
  • 23,434
  • 46
  • 157
  • 277

2 Answers2

10
  • Use min and step to prevent the spinner from going negative. (reference: this SO answer)
  • Use ngModelChange to handle the case where a user tries to type in a negative number.
@Component({
  selector: 'my-app',
  template: `{{title}}
    <p><input type="number" min="0" step="1" [ngModel]="model"
        (ngModelChange)="validate($event)">`,
})
export class AppComponent {
  title = `Angular - RC.1`;
  model = 3;
  validate(value)  {
    value < 0 ? this.model = 0 : this.model = value;
  }
}

Plunker

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • 1
    Thank you, but how I can know on the `validate` method which model im working on, if I'm looping on a list of items? `[(ngModel)]="items[i].amount"` – TheUnreal May 20 '16 at 08:06
  • Why is the validate method triggered twice when clicking the up/down buttons? – tdhulster Aug 09 '16 at 22:27
  • @TheUnreal, pass `i` in the method call: `validate($event, i)`, then lookup the element in the method. – Mark Rajcok Aug 10 '16 at 02:59
  • @tdhulster, good question... I don't know why. It also happens if you use the up/down arrow keys. – Mark Rajcok Aug 10 '16 at 03:15
  • @tdhulster, maybe it is triggered twice because you are not in prod mode... ("Angular is running in the development mode. Call enableProdMode() to enable the production mode." is gonna be shown in the console) – Guntram May 23 '17 at 14:50
0

Using the min and digits validators from the module ng2-validation would do the trick for you.

osolmaz
  • 1,873
  • 2
  • 24
  • 41