ngx-material中Datepicker的日期格式化和选择语系

2,378 阅读3分钟

本文主要介绍ngx-material的Datepicker组件中对设定日期的格式和设定组件的语系。对于Datepicker的使用将一笔带过,详细使用可查看angular官网

Datepicker组件的简单使用

  1. 下载安装ngx-material包,本人使用的是angular5,所以下载的ngx-material是5.2.5版本(PS:如果install失败,请使用淘宝镜像,自行百度一下)。具体ngx-material的使用点这里。

    npm install @angular/material@5.2.5 --save
    
  2. 在module中引入MatDatepickerModule

    /**专门创建一个module,来管理ng-material模块的引入*/
    import { MatDatepickerModule } from '@angular/material';
    
    @NgModule({
      imports:[MatDatepickerModule],
      exports: [MatDatepickerModule]
    })
    
    export class MyMaterialModule { }
    
  3. 在html中使用mat-datepicker组件

    <!-- 在html中使用datepicker -->
    <mat-form-field >
        <mat-label>日历使用demo</mat-label>
        	<input matInput [matDatepicker]="picker1" placeholder="yyyy/mm/dd"			  name="date" [(ngModel)]="_date">
            <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
            <mat-datepicker #picker1></mat-datepicker>
    </mat-form-field>
    

设定Datepicker的日期格式

对于日期格式的处理,有2种方式。第一种是引入MatNativeDateModule,它是ng-material自带的;第二种是使用moment.js,引入MatMomentDateModule,需要通过npm安装。

  1. 引入MatNativeDateModule模式

    使用MatNativeDateModule,不需要安装任何额外的包。

    /**专门创建一个module,来管理ng-material模块的引入*/
    import { MatDatepickerModule } from '@angular/material';
    import { MatMomentDateModule } from '@angular/material-moment-adapter';
    import { NativeDateAdapter } from "@angular/material";
    
    @NgModule({
      imports:[MatDatepickerModule,MatMomentDateModule],
      exports: [MatDatepickerModule,MatMomentDateModule],
      providers:[
        { provide: DateAdapter, useClass: MyDateAdapter },
        { provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS },
      ]
    })
    
    export class MyMaterialModule { }
    
    export class MyDateAdapter extends NativeDateAdapter {
        format(date: Date, displayFormat: Object): string {
            if (displayFormat === "input") {
                const day = date.getDate();
                const month = date.getMonth() + 1;
                const year = date.getFullYear();
                return year + '/' + this._to2digit(month) + '/' + this._to2digit(day);
            } else {
                return date.toDateString();
            }
        }
    
        private _to2digit(n: number) {
            return ('00' + n).slice(-2);
        }
    }
    
    
    export 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' },
        }
    };
    
  2. 引入MatMomentDateModule模式

    使用MatMomentDateModule,需要安装@angular/material-moment-adapter和moment,安装时注意版本要和自己使用的angular版本相对应,否则可能出现不了你想要的效果。如果没有安装moment,在你的项目引入MatMomentDateModule之后,运行项目会报很多的红色错误。

    1. 安装@angular/material-moment-adapter和moment

      //安装@angular/material-moment-adapter,一定要注意版本,和你的angular版本相匹配
      npm install @angular/material-moment-adapter@5.2.5 --save
      //安装moment(如果没有安装moment,在项目引入MatMomentDateModule后运行项目会报错)
      npm install moment --save
      
    2. 引入MatMomentDateModule,并且创建一个自定义的MY_DATE_FORMATS代替原来的MAT_DATE_FORMATS。

      /**专门创建一个module,来管理ng-material模块的引入*/
      import { MatDatepickerModule } from '@angular/material';
      import { MatMomentDateModule } from '@angular/material-moment-adapter';
      
      @NgModule({
        imports:[MatDatepickerModule,MatMomentDateModule],
        exports: [MatDatepickerModule,MatMomentDateModule],
        providers:[
          {provide:MAT_DATE_FORMATS,useValue:MY_DATE_FORMATS}
        ]
      })
      
      export class MyMaterialModule { }
      
      export const MY_DATE_FORMATS = {
          parse: {
              dateInput: 'YYYY/MM/DD'
          },
          display: {
              dateInput: 'YYYY/MM/DD',
              monthYearLabel: 'YYYY MMM',
              dateA11yLabel: 'YYYY/MM/DD',
              monthYearA11yLabel: 'YYYY MMM'
          }
      };
      

设定Datepicker的语系

如果要设定Datepicker的语系,建议在日期格式化时就使用第二种方式——引入MatMomentDateModule模式,这样可以在设定语系时更加方便。只需要在providers中修改MAT_DATE_LOCALE的值,改成自己想要的语系。那么moment支持哪些语系呢?答案在这里我们也可以根据项目中语序的变化,改变Datepicker的语系,使用DateAdapter的setLocale方法。

/**专门创建一个module,来管理ng-material模块的引入*/
import { MatDatepickerModule,DateAdapter } from '@angular/material';
import { MatMomentDateModule } from '@angular/material-moment-adapter';
import { TranslateService, LangChangeEvent } from '@ngx-translate/core';
@NgModule({
  imports:[MatDatepickerModule,MatMomentDateModule],
  exports: [MatDatepickerModule,MatMomentDateModule],
  providers:[
    {provide:MAT_DATE_FORMATS,useValue:MY_DATE_FORMATS},
    /**多加这一行*/
    { provide: MAT_DATE_LOCALE, useValue: 'zh-CN' },
  ]
})

export class MyMaterialModule {
  /**根据项目中语系的变化而变化*/
constructor(private translate: TranslateService, private adapter: DateAdapter<any>) {
    translate.onLangChange.subscribe((params: LangChangeEvent) => {
      let lang = 'zh-CN';
      switch (params.lang) {
        case 'zh_cn':
          lang = 'zh-CN';
          break;
        case 'zh_tw':
          lang = 'zh-TW';
          break;
        case 'en':
          lang = 'en-GB';
          break;
        default:
          break;
      }
      adapter.setLocale(lang);
    });
  }
}

export const MY_DATE_FORMATS = {
    parse: {
        dateInput: 'YYYY/MM/DD'
    },
    display: {
        dateInput: 'YYYY/MM/DD',
        monthYearLabel: 'YYYY MMM',
        dateA11yLabel: 'YYYY/MM/DD',
        monthYearA11yLabel: 'YYYY MMM'
    }
};