ngx-material中Datepicker的日期格式化和選擇語系

本文主要介紹ngx-material的Datepicker組件中對設定日期的格式和設定組件的語系。對於Datepicker的使用將一筆帶過,詳細使用可查看angular官網html

Datepicker組件的簡單使用

  1. 下載安裝ngx-material包,本人使用的是angular5,因此下載的ngx-material是5.2.5版本(PS:若是install失敗,請使用淘寶鏡像,自行百度一下)。具體ngx-material的使用點這裏。git

    npm install @angular/material@5.2.5 --save
    複製代碼
  2. 在module中引入MatDatepickerModulegithub

    /**專門建立一個module,來管理ng-material模塊的引入*/
    import { MatDatepickerModule } from '@angular/material';
    
    @NgModule({
      imports:[MatDatepickerModule],
      exports: [MatDatepickerModule]
    })
    
    export class MyMaterialModule { }
    複製代碼
  3. 在html中使用mat-datepicker組件typescript

    <!-- 在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安裝。npm

  1. 引入MatNativeDateModule模式bash

    使用MatNativeDateModule,不須要安裝任何額外的包。ide

    /**專門建立一個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模式post

    使用MatMomentDateModule,須要安裝@angular/material-moment-adapter和moment,安裝時注意版本要和本身使用的angular版本相對應,不然可能出現不了你想要的效果。若是沒有安裝moment,在你的項目引入MatMomentDateModule以後,運行項目會報不少的紅色錯誤。ui

    1. 安裝@angular/material-moment-adapter和momentthis

      //安裝@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'
    }
};
複製代碼
相關文章
相關標籤/搜索