Reputation: 499
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;
}
}
Upvotes: 1
Views: 777
Reputation: 11982
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
Upvotes: 0
Reputation:
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);
Upvotes: 2