【问题标题】:Change date format in mat-datepicker dynamically动态更改 mat-datepicker 中的日期格式
【发布时间】:2021-04-23 02:28:22
【问题描述】:

可以通过按钮更改日期格式吗?例如,默认格式是 DD/MM/YYYY,但是当我单击按钮时,我会注册新格式,例如 YYYY/MM/DD,这可能吗?我从那个代码开始:

部分ts文件

const moment = _rollupMoment || _moment;
export const MY_FORMATS = {
    parse: {
        dateInput: 'DD/MM/YYYY',
    },
    display: {
        dateInput: 'DD/MM/YYYY',
        monthYearLabel: 'MM YYYY',
        dateA11yLabel: 'DD/MM/YYYY',
        monthYearA11yLabel: 'MM YYYY',
    },
};


providers: [{
        provide: DateAdapter,
        useClass: MomentDateAdapter,
        deps: [MAT_DATE_LOCALE]
    },
    {
        provide: MAT_DATE_FORMATS,
        useValue: MY_FORMATS
    },
]



changeFormat() {
    ????????
}

html 文件:

   <input matInput [matDatepicker]="picker" placeholder="mm.dd.yyyy"
                      (click)="picker.open()" #birthInput>
               <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
               <mat-datepicker #picker></mat-datepicker>
 <span (click)="changeFormat()"></span>

感谢您的帮助。

【问题讨论】:

    标签: angular angular-material angular-moment


    【解决方案1】:

    您正在定义一个固定的 MY_FORMAT,但您可以定义一个类似的类

    export class MyFormat{
      value=1;
      constructor(){}
      get display(){
        return this.value==1?
         {
            dateInput: 'LL',
            monthYearLabel: 'MMM YYYY',
            dateA11yLabel: 'LL',
            monthYearA11yLabel: 'MMMM YYYY',
          }:{
            dateInput: 'DD/MM/YYYY',
            monthYearLabel: 'MM YYYY',
            dateA11yLabel: 'DD/MM/YYYY',
            monthYearA11yLabel: 'MM YYYY',
        }
      }
      get parse(){
        return this.value==1?{
            dateInput: 'LL',
          }:{
          dateInput: 'DD/MM/YYYY'
          }
      }
      
    }
    

    然后在提供者中你使用这个类

      providers: [
        {provide: MAT_DATE_FORMATS, useClass: MyFormat},
      ],
    

    最后,您在组件的构造函数中注入提供者以访问变量“value”

      constructor(@Inject(MAT_DATE_FORMATS) public config: MyFormat){}
    

    嗯,你需要,当改变格式时“重绘”dateForm,例如

      change(){
        this.config.value=this.config.value==1?2:1 //we change the "value"
        this.date=new FormControl(this.date.value)  //give the value
      }
    

    但是,请注意,您需要使用 CustomDateAdapter 或使用 MomentDateAdapter

    使用 MomentDateAdapter 将其导入模块 MomentDateModule

    @NgModule({
      imports: [
        ...
        MomentDateModule,
      ],
    

    如果你想使用 CustomDateAdapter,你可以使用类似

    export class CustomDateAdapter extends NativeDateAdapter {
    
      formato="YYY/MM/DD"
      parse(value: any) {
        const parts = value.match(/\d{1,4}/g);
        if (parts && parts.length == 3) {
          const order = this.formato.match(/Y{2,4}|M{1,2}|D{1,2}/g);
          if (order) {
            const year = +parts[
              order.indexOf("YYYY") < 0
                ? order.indexOf("YY")
                : order.indexOf("YYYY")
            ];
            const month = +parts[
              order.indexOf("MM") < 0 ? order.indexOf("M") : order.indexOf("MM")
            ];
            const day = +parts[
              order.indexOf("DD") < 0 ? order.indexOf("D") : order.indexOf("DD")
            ];
            return new Date(year<100?year+2000:year, month - 1, day);
          }
        }
        return null;
      }
      format(date: any, displayFormat: any): string {
        if (displayFormat=="MMM YYYY")
          return this.getMonthNames('long')[date.getMonth()]+' '+date.getFullYear()
    
        const result= displayFormat
          .replace("YYYY", date.getFullYear())
          .replace("YY", date.getYear())
          .replace("MMM", this.getMonthNames('long')[date.getMonth()])
          .replace("MM", ("00" + (date.getMonth() + 1)).slice(-2))
          .replace("M", date.getMonth() + 1)
          .replace("DD", ("00" + date.getDate()).slice(-2))
          .replace("M", date.getDate())
          return result;
      }
    }
    

    然后您在构造函数中注入适配器并更改“格式”值

    constructor(@Inject(MAT_DATE_FORMATS) private config: MyFormat,
                @Inject(DateAdapter) private customDateAdapter:CustomDateAdapter) {
        this.config.value = 1;
        this.customDateAdapter.formato='YYYY/MM/DD'
      }
    
      change() {
        this.config.value = this.config.value == 1 ? 2 : 1;
        this.customDateAdapter.formato=this.config.value==1?'DD/MM/YYYY' : 'YYYY/MM/DD';
        this.date = new FormControl(this.date.value);
      }
    

    你可以看到a stackblitz using MomentAdapter

    你可以看到a stackblitz using CustomDateAdapter

    【讨论】:

    • 这真的很棒。我能够注入@Inject(LOCALE_ID) public locale: string 并在开关中使用this.locale 按文化进行不同的日期解析。我正在使用 Luxon,但内置的“本地化”格式不够灵活/全面。唯一的缺点似乎是我必须在每个使用日期选择器的组件中注入它,而不是在模块/应用程序中只注入一次,但我可以忍受。
    【解决方案2】:

    您可以为此使用当前的解决方法。

    请检查这个例子 https://stackblitz.com/edit/angular-mat-datepicker-xrwgmu?file=app/datepicker-overview-example/datepicker-overview-example.component.ts

    <mat-form-field class="mt-2">
        <input
              matInput
              placeholder="Date"
              (focus)="datePicker.open();"
              [value]="dateInput.value | date:format">
        <input
              #dateInput
              class="hidden-dateinput"
              [matDatepicker]="datePicker">
        <mat-datepicker-toggle matSuffix [for]="datePicker"></mat-datepicker-toggle>
        <mat-datepicker #datePicker></mat-datepicker>
    </mat-form-field>
    

    这是在 style.css 中

    .hidden-dateinput {
      opacity: 0;
      position: absolute;
      width: 1px;
      height: 1px;
    }
    

    format 可以动态更改

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-08
      • 2020-12-17
      相关资源
      最近更新 更多