Afs*_*ghi 4 datepicker persian angular angular5
Angular2 Material Component有一个DatePicker,以默认格式显示日期.
并且仅支持"fa-IR"本地更改.
如何格式化以显示波斯日期?
小智 12
以下步骤应该有所帮助:
1:在module.ts中加载所有必需的模块:
import { MatDatepickerModule, NativeDateAdapter, DateAdapter, MAT_DATE_FORMATS,MAT_DATE_LOCALE} from '@angular/material';
Run Code Online (Sandbox Code Playgroud)
2:使用NPM安装jalali-moment:
npm install jalali-moment
Run Code Online (Sandbox Code Playgroud)
3:将jalali日期导入您的应用:
import * as moment from 'jalali-moment';
Run Code Online (Sandbox Code Playgroud)
如果使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
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' }
}
}
Run Code Online (Sandbox Code Playgroud)
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 }
],
})
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
8:当用户手动更改日期输入时,还要正确地弹出显示日期,你必须将下面的代码和方法添加到ts文件中,你将你的datepicker控件放到它的html文件或模板中
添加以下mothod来处理输入更改事件
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;
}
Run Code Online (Sandbox Code Playgroud)
由于datepicker显示的日期有问题,我强制编辑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));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2943 次 |
| 最近记录: |