如何在服务层的 Formly 表单中格式化 Angular Material 日期选择器(不是显示格式) [英] How to format Angular Material date-picker inside Formly form for service layer (not display format)
问题描述
我想在 Angular Material 日期选择器上将我的日期值公开为仅日期(yyyy-MM-dd").目前,默认日期值为 ISO 格式(包括时间).
I would like to expose my date value as date only ("yyyy-MM-dd") on an Angular Material date picker. Currently, the default date value is an ISO format (includes time).
我有一个初学者Stackblitz 项目与所需的设置.formly-datepicker.type
是我想要集中转换的地方,以便模型中使用的任何日期都可以为服务层正确格式化.
I have a starter Stackblitz project with the the required setup. The formly-datepicker.type
is where I would like to centralize the conversion so that any date used in the model will be formatted properly for the service layer.
我以集中方式完成它的尝试之一是使用 Angular ControlValueAccessor,但该值永远不会更新.ControlValueAccessor Stackblitz
One of my attempts to accomplish it in a centralized manner is using the Angular ControlValueAccessor, but the value is never updated. ControlValueAccessor Stackblitz
在示例 Stackblitz 中,更改日期并单击提交后,我需要返回的值类似于:{mydate":1940-03-11"}
(没有时间信息).
In the example Stackblitz, after changing the date and clicking Submit the value I need returned would be something like: {"mydate":"1940-03-11"}
(without the time information).
推荐答案
所以,我想我有解决方案可以让您将 mat datepicker
显示为 ("yyyy-MM-dd")
格式.安装到依赖项 "@angular/material-moment-adapter": "^11.1.2"
和 "moment": "^2.18.1"代码>(都是当前版本).然后在您的
formly-datepicker-type.component.ts
文件中导入这两个库.
So , I think I have solution for you to display mat datepicker
as ("yyyy-MM-dd")
format. To do that Install to dependencies "@angular/material-moment-adapter": "^11.1.2"
and "moment": "^2.18.1"
(both are current version). Then import in your formly-datepicker-type.component.ts
file these 2 libraries.
import {MomentDateAdapter} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
然后在您的 formly-datepicker-type.component.ts
文件中添加如下所示的日期格式.=>
Then add a date format like below in your formly-datepicker-type.component.ts
file.=>
export const MY_FORMATS = {
parse: {
dateInput: 'LL',
},
display: {
dateInput: 'YYYY-MM-DD',
monthYearLabel: 'YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'YYYY',
},
};
之后更新 @Component
,添加如下提供者 =>
After that Update @Component
by adding providers like below =>
@Component({
selector: "app-formly-datepicker-type",
templateUrl: "./formly-datepicker-type.component.html",
styleUrls: ["./formly-datepicker-type.component.css"],
providers: [
{provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
]
})
最后,日期时间将按需要显示.
注意: 我已经更新了 stackblitz 的示例代码.请查看我的演示链接 =>Stackblitz mat-datepicker 日期时间格式.
Finally, Date time will show as wanted.
Note: I have updated you sample code of stackblitz. Please check my demo link =>Stackblitz mat-datepicker Date-Time Format.
这篇关于如何在服务层的 Formly 表单中格式化 Angular Material 日期选择器(不是显示格式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!