0

I have an input field for a datepicker - the user can enter the minutes using the keyboard and when they enter a value less than 10 it will auto prepend the inital zero - so the time time 10:1 looks like 10:01 (there is an hour input and an minute input field) - the problem I have is it displays the zero instantly so it makes it difficult for editing the minute field with different values - how is the best way to delay to displayMinute function using a timeout or similar method so that when called it delays executing this by a second or so?

// function to prepend 0 to a minute if the minute is under 10
Calendar.prototype.displayMinute = function (minute) {
   minute = (minute < 10) ? '0' + minute : minute;
   return minute;
};

template: "<input type=\"text\" (keyup)='updateMinuteInput($event)' [value]=\"displayMinute(currentMinute)\" >\n",
Zabs
  • 13,852
  • 45
  • 173
  • 297
  • 1
    *Masked Input* components are the simplest way to do this, a timer seems very clunky. – Alex K. Dec 14 '18 at 12:54
  • 1
    I do agree with @AlexK. that it's a far better practice to use a masked input instead, so that the user won't get confused if the value somehow change. For instance, you may check this library: https://github.com/text-mask/text-mask – briosheje Dec 14 '18 at 12:57

1 Answers1

2

Instead of updating the displayed value, you should update the value in the underlying input.

You can then use a debounce on the input event so that it is delayed.

class Calendar {

  constructor() {
    this.updateMinuteInput = EventEmitter();
    this.updateMinuteInput.debounceTime(1000).do(() => this.padMissingZero)
  }


  // function to prepend 0 to a minute if the minute is under 10
  padMissingZero = function () {
     minute = this.value.split(':')[1];
     if (minute === null || minute === undefined) return;
     minute = parseInt(minute, 10);
     minute = (minute < 10) ? '0' + minute : minute;
     this.value = this.value.split(':')[0] + minute
  };
}

template: "<input type=\"text\" [value]="value" (keyup)='updateMinuteInput($event)'>\n",

see Angular and debounce for a more complete example

codebreach
  • 2,155
  • 17
  • 30