0

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?

1
  • 2
    Unfortunately, this seems to be a limitation with the native <input type="number"/> element. It will only display error message on submit: jsfiddle.net/TAftq (get from another stackoverflow topic). Tested in Chrome. It seems that Firefox also does not restrict input values: bugs.chromium.org/p/chromium/issues/detail?id=365196 I suppose that you will need to use 3rd party component to solve this issue. Commented Nov 23, 2016 at 12:59

1 Answer 1

2

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'
    
Sign up to request clarification or add additional context in comments.

1 Comment

it's ugly but it warks. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.