ngx-timepicker-field 24小时制下上午时间无法显示双位数问题
Hey there! I’ve run into similar quirks with ngx-timepicker-field before, so let’s work through getting those leading zeros to show up for morning times (like turning 9:30 into 09:30). Here are a few practical solutions to try:
1. Use the Component’s Built-in leadingZero Property
First off, many versions of ngx-timepicker-field have a dedicated property to enforce leading zeros, even when using 24-hour format. Update your template to include this attribute:
<ngx-timepicker-field [format]="24" [leadingZero]="true" [(ngModel)]="selectedTime"> </ngx-timepicker-field>
This is the quickest fix if your component version supports it—double-check the official docs for your specific release to confirm the property exists.
2. Format Output with Angular’s DatePipe
If the leadingZero option isn’t available, you can manually format the time using Angular’s built-in DatePipe to force 2-digit hours and minutes.
First, ensure DatePipe is imported in your module, then use it in your template when displaying the time:
{{ selectedTime | date:'HH:mm' }}
The HH specifier guarantees a 24-hour format with leading zeros, while mm keeps minutes as two digits.
3. Build a Custom Pipe for Full Control
If you need more flexibility (or if the above methods don’t work), create a simple custom pipe to tweak the time string directly:
- Generate the pipe via CLI:
ng generate pipe doubleDigitTime
- Update the pipe logic to pad single-digit hours:
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'doubleDigitTime' }) export class DoubleDigitTimePipe implements PipeTransform { transform(timeString: string): string { if (!timeString || !timeString.includes(':')) return timeString; const [hour, minute] = timeString.split(':'); const formattedHour = hour.padStart(2, '0'); return `${formattedHour}:${minute}`; } }
- Use the pipe in your template:
{{ selectedTime | doubleDigitTime }}
4. Upgrade the Component Version
If none of the above resolve the issue, it might be a bug in an older release of ngx-timepicker-field. Try upgrading to the latest stable version:
npm install ngx-timepicker-field@latest --save
内容的提问来源于stack exchange,提问作者Nico Alvarez

