gpt4 book ai didi

angular - Angular 2 中的 Material 组件波斯日期选择器

转载 作者:太空狗 更新时间:2023-10-29 17:42:26 24 4
gpt4 key购买 nike

Angular2 Material Component 有一个以默认格式显示日期的 DatePicker。

并且只支持将本地更改为“fa-IR”。

如何格式化它以显示波斯日期?

最佳答案

以下步骤应该有所帮助:

1:加载module.ts中所有需要的模块:

import { MatDatepickerModule, NativeDateAdapter, DateAdapter, MAT_DATE_FORMATS,MAT_DATE_LOCALE} from '@angular/material/datepicker';

2:使用 NPM 安装 jalali-moment:

 npm install jalali-moment

3:在您的应用中导入 jalali 日期:

import * as moment from 'jalali-moment';

如果使用system.js,必须在system.config.js中声明才能运行app

4:编写一个自定义类来覆盖默认的日期格式机制

export class CustomDateAdapter extends NativeDateAdapter {
constructor(matDateLocale: string) {
super(matDateLocale, new Platform());
}
format(date: Date, displayFormat: object): string {
var faDate = moment(date.toDateString()).locale('fa').format('YYYY/MM/DD');
return faDate;
}
}

5:写一个常量来定义你的自定义日期格式

const MY_DATE_FORMATS = {
parse: {
dateInput: { month: 'short', year: 'numeric', day: 'numeric' }
},
display: {
dateInput: 'input',
monthYearLabel: { year: 'numeric', month: 'short' },
dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },
monthYearA11yLabel: { year: 'numeric', month: 'long' }
}
}

6:MatDatepickerModule 必须添加到您的@NgModule。在 @NgModule 中编辑您的提供者部分,以将添加的类引入您的应用:

@NgModule({
imports: [
MatDatepickerModule,
],
providers: [
{ provide: MAT_DATE_LOCALE, useValue: 'fa-IR' },
{ provide: DateAdapter, useClass: CustomDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS }
],
})

7:将日期选择器添加到您的 html 页面:

<mat-form-field>
<input #dateInput matInput [matDatepicker]="picker" [(ngModel)]="date" (change)="dateChange($event,dateInput,picker)" placeholder="انتخاب تاریخ">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>

8: 此外,为了在用户手动更改日期输入时 datepicker 弹出正确显示日期,您必须将以下代码和方法添加到 ts 文件中,您将 datepicker 控件放入其 html 文件或模板中

添加以下方法来处理输入更改事件

 public dateChange(event: any, dateInput: any,picker:any) {
var faDate = dateInput.value;
moment.locale('fa');
var enDateMomentFormat = moment(faDate).locale('en');
var enDate = new Date(enDateMomentFormat.toLocaleString());
picker._validSelected = enDate;
picker.startAt = enDate;
}

由于日期选择器显示的日期有问题,我不得不编辑 material.umd.js 来更正它。在地址:node_modules/@angular/material/bundles/material.umd.js在 :10947 <==> 也可以搜索“MatMonthView.prototype._createWeekCells =”如下编辑函数的结束行

let displayValue = ariaLabel.split('/')[2];
this._weeks[this._weeks.length - 1]
.push(new MatCalendarCell(i + 1, Number(displayValue), ariaLabel, enabled));

关于angular - Angular 2 中的 Material 组件波斯日期选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48581641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com