材料成分波斯日期选择器角度为2

前端之家收集整理的这篇文章主要介绍了材料成分波斯日期选择器角度为2前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Angular2 Material Component有一个DatePicker,以默认格式显示日期.

@H_502_8@

并且仅支持“fa-IR”本地更改.@H_502_8@

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

解决方法

以下步骤应该有所帮助:

@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@

4:编写自定义类以覆盖默认日期格式机制@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;
  }
}

5:编写一个定义自定义日期格式的常量@H_502_8@

@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 }
  ],})

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

@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@

添加以下mothod来处理输入更改事件@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));

猜你在找的Angularjs相关文章