1

I am trying to implement a time picker using html5 input type number in angular2 as shown below:

<input type="number" [(ngModel)]="hour" (change)="checkHours();" name="one" min="1" max="12">
<input type="number" [(ngModel)]="minutes" (change)="checkMinutes();" name="two" min="0" max="59">

On changing the value (manually entering or by using the up/down arrows in input type), a function should be triggered so that i could modify it in typescript so that single digit time in hours/minutes to be displayed as two-digit ones. as:

if i select/enter values as hour 5 and minute 3 then after function call it should display as "05" in hours input and "03" in minutes input box. But it seems there is some issues like: this.hours does not have the changed value in it. I am doubtful whether I could manipulate number type as string? Please help. Thanks in advance. Any alternate solutions also welcome.

public checkHours(){
  if (this.hours <= 9){
    this.hours = "0" + this.hours;
  }
}

public checkMinutes(){
  if (this.minutes <= 9){
    this.minutes = "0" + this.minutes;
  }
}

1
  • Can you please ellobrate on what issue you are facing? Commented Aug 20, 2018 at 12:14

2 Answers 2

2

The fastest on is this one :

function twoDigits(value) {
  return ('0'  + value).slice(-2);
}

console.log(twoDigits('1'));
console.log(twoDigits('01'));

In your case :

twoDigits(value: number) {
  value = ('0' + value).slice(-2);
}

To call it :

this.twoDigits(this.hours);
Sign up to request clarification or add additional context in comments.

Comments

0

the problem is because you define hours as number but in your function you assign it a string value and it's not correct:

and you can try:

public checkHours(){
  let hours=''
  if (this.hours <= 9){
    hours = "0" + this.hours;
  }
  console.log(hours)
}

public checkMinutes(){
  let minutes='';
  if (this.minutes <= 9){
    minutes = "0" + this.minutes;
  }
    console.log(minutes)
}

html :

<input type="number" [(ngModel)]="hours" (change)="checkHours();" name="one" min="1" max="12">
<input type="number" [(ngModel)]="minutes" (change)="checkMinutes();" name="two" min="0" max="59">

working demo

2 Comments

in JS variables aren't typed : you can switch from number to string and vice versa. In typescript, you declare your variables to be both, for instance hours: number & string;. The issue doesn't come from that.
you are right but the problem is you can't assign string to input type number, so it will not work correct.

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.