subarroca
subarroca

Reputation: 861

angular2 input number error

I'm trying to create a time picker component having hour, minute, second in separate inputs. This should be controlled between 2 different timestamps for min and max.

Separate fields work ok, min and max work ok but input does not.

I have

<input
  type = number
  name = hour
  [ngModel] = _hour
  (ngModelChange) = updateHour($event)
  [min] = _minHour
  [max] = _maxHour
  placeholder = 00>

When entering 88 sets maximum to 23 (as expected) then entering another 8 sets ngModel to 23 (as expected) but input displays 238, (which is wrong)

I've done a plunker to https://plnkr.co/edit/XUWOim?p=preview

Any ideas?

Upvotes: 0

Views: 546

Answers (1)

Stopee
Stopee

Reputation: 249

My solution:

  1. Pass input element as parameter in updateHour function

    <input #hour
          type = number
          name = hour
          [ngModel] = _hour
          (ngModelChange) = "updateHour($event, hour)"
          [min] = _minHour
          [max] = _maxHour
          placeholder = 00>
    
  2. Set input value to correct value( after validation)

    updateHour(value:string, hourElement: ElementRef){
          let intValue: number = Math.max(this._minHour, Math.min(this._maxHour, parseInt(value))) || 0;
          hourElement.value = intValue;
          this.time.setHours(intValue);
          }
    

    Don't forget to import ElementRef

          import {Component, NgModule, OnInit, ElementRef} from '@angular/core'
    

Upvotes: 2

Related Questions