我正在使用 ngx-mat-datetime-picker 使用 Angular react 形式输入日期时间。
我的表单输入:
<mat-form-field (click)="picker.open()" fxFlex="50%" fxFlex.lt-md="50%" fxFlex.lt-sm="50%">
<input matInput placeholder="{{ 'START TIME' | translate }}" [min]="today" [ngxMatDatetimePicker]="picker" formControlName="startTime">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<ngx-mat-datetime-picker enableMeridian="true" touchUi="true" [showSeconds]="showSeconds" #picker></ngx-mat-datetime-picker>
<mat-error *ngIf="addForm.get('startTime').invalid && (addForm.get('startTime').dirty || addForm.get('startTime').touched)" class="alert alert-danger">
<mat-error *ngIf="addForm.get('startTime').errors.required">
{{'THIS FIELD IS REQUIRED'|translate}}
</mat-error>
</mat-error>
</mat-form-field>
现在我使用子午线时间输入,我选择使用 AM、PM 输入的时间,但当它显示在表单 View 中时,它以 24 小时格式显示时间。我想在选择后以 12 小时格式显示时间。我尝试使用管道变换来转换输入。但它现在不起作用..
在表单值更改函数中,
this.addForm.valueChanges.subscribe((value: any) => {
if (value.startTime) {
this.addForm.patchValue(
{
startTime: this.timeTransform.transform(value.startTime),
},
{
emitEvent: false,
}
);
console.log("value is", this.addForm.get('startTime').value);
}
this.changeDetector.detectChanges();
});
}
该值打印正确,但未反射(reflect)在 View 中
最佳答案
我有一段时间遇到同样的问题,我找到了这个日期时间控件的解决方案,也许它并不完美,但它有效:
对于您的情况,仅使用时间格式:
this.myForm.get('date').value.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
html代码:
<input class="input-calendar" nz-input placeholder="Choose a date" formControlName="publish" [min]="minDate" [max]="maxDate">
<input formControlName="date" [ngxMatDatetimePicker]="picker" style="visibility: hidden; width: 1px;">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<ngx-mat-datetime-picker #picker [showSpinners]="true"
[showSeconds]="false" [stepHour]="1"
[stepMinute]="1" [stepSecond]="1" [touchUi]="false" [color]="color"
[enableMeridian]="true"
[disableMinute]="false" [hideTime]="false">
</ngx-mat-datetime-picker>
组件代码:
ngAfterViewChecked() {
this.myForm.valueChanges.subscribe((value: any) => {
if (value.date) {
this.myForm.patchValue(
{
publish: this.myForm.get('date').value.toLocaleString('en-US',
{
year: 'numeric', day: '2-digit', month: '2-digit', hour: 'numeric',
minute: 'numeric', hour12: true })
},
{
emitEvent: false,
}
);
}
this.cd.detectChanges();
});
}
问候,
关于angular - 更改日期时间选择器输入 react 形式中的时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62167547/