解决方法
以下步骤应该有所帮助:
@H_502_8@
1:在module.ts中加载所有必需的模块:@H_502_8@
@H_502_8@
import { MatDatepickerModule,NativeDateAdapter,DateAdapter,MAT_DATE_FORMATS,MAT_DATE_LOCALE} from '@angular/material';
2:使用NPM安装jalali-moment:@H_502_8@
@H_502_8@
npm install jalali-moment
3:将jalali日期导入您的应用:@H_502_8@
@H_502_8@
import * as moment from 'jalali-moment';
如果使用system.js,则必须在system.config.js中声明它以运行app@H_502_8@
@H_502_8@
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; } }
@H_502_8@
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中编辑您的提供者部分,将添加的类引入您的应用:@H_502_8@
@H_502_8@
@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 } ],})
@H_502_8@
<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:当用户手动更改日期输入时,还要正确地弹出显示日期,你必须将下面的代码和方法添加到ts文件中,你将你的datepicker控件放到它的html文件或模板中@H_502_8@
@H_502_8@
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; }
由于datepicker显示的日期有问题,我强制编辑material.umd.js来纠正它.
在地址:node_modules/@angular/material/bundles/material.umd.js
在线:10947< ==>你也可以搜索“MatMonthView.prototype._createWeekCells =”
编辑功能的结束行如下@H_502_8@
@H_502_8@
let displayValue = ariaLabel.split('/')[2]; this._weeks[this._weeks.length - 1] .push(new MatCalendarCell(i + 1,Number(displayValue),ariaLabel,enabled));