如何在运行时更改 Angular Material Datepicker 格式 [英] How to change Angular Material Datepicker format in run-time

查看:39
本文介绍了如何在运行时更改 Angular Material Datepicker 格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Material 设计开发 Angular 应用,并且我正在使用 Moment.js 来解析和格式化日期.

I'm working on an Angular App with Material Design, and I'm using Moment.js to parse and format dates.

在我的一个页面中,我有一个 Material 的日期选择器.我已经按照材料的指导方针让 Datepicker 使用 moment 对象 - 而不是原生的 Date 对象.

In one of my pages I have a Material's Datepicker. I have followed the material's guide-lines to make the Datepicker work with moment object - instead on the native Date object.

我还设法以某种格式在日期选择器中显示日期.但是这种格式在组件的提供者中是硬编码的.如何根据用户偏好在运行时更改格式?

Also I managed to display the Date in the Datepicker in a certain format. But this format in hard coded in the Component's providers. How can I change the format during run-time, according to the user preferences?

我已经安装了 npm 的软件包:

I've installed npm's packages:

$ npm i moment -S
$ npm i @angular/material-moment-adapter -S

// app.module.ts
import { MatMomentDateModule } from '@angular/material-moment-adapter'
...
@NgModule({
  imports: [
    MatMomentDateModule,
...

// demo.component.ts
import * as moment from 'moment';
import { MAT_DATE_FORMATS } from '@angular/material/core';
const MY_FORMATS = {
  parse: {
    dateInput: 'LL',
  },
  display: {
    dateInput: 'LL',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};
@Component({
  selector: 'app-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.scss'],
  providers: [
    { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS },
  ],
})
export class DemoComponent {
   public dateVal = moment();
}

// demo.component.html
<mat-form-field>
  <input matInput [matDatepicker]="myDatePicker" [(ngModel)]="dateVal">
  <mat-datepicker-toggle matSuffix [for]="myDatePicker"></mat-datepicker-toggle>
  <mat-datepicker #myDatePicker></mat-datepicker>
</mat-form-field>

如您所见,日期格式是在组件的提供程序中定义的.如何在运行时更改此设置?

As you can see, the date-format is defined in the Component's providers. How can I change this in run-time?

可以在此处找到工作示例:
https://stackblitz.com/angular/mgaargebgpd?file=app%2Fdatepicker-formats-example.ts

A working example could be found here:
https://stackblitz.com/angular/mgaargebgpd?file=app%2Fdatepicker-formats-example.ts

推荐答案

OK,所以我终于找到了在运行时更改 mat-date-picker 格式的方法(文档没有一点帮助都没有).

OK, so I finally find a way to change the mat-date-picker format during run-time (the documentation didn't help at all).

您可能已经有这样的服务,如果没有,您应该创建一个,这样您就可以在一个地方控制日期格式.

You probable already have a service like this, if no you should create one, so you could control the date-formatting in one place.

// date-time.service
import { Injectable } from '@angular/core';
import * as moment from 'moment';

@Injectable({ providedIn: 'root' })
export class DateTimeService
{
  public getFormat(): string
  {
    return "DD-MM-YYYY"; // add you own logic here
  }
  public getLocale(): string
  {
    return "he-IL"; // add you own logic here
  }  
}

第 2 步 - 创建一个 CustomDateAdapter,它将负责在运行时解析日期

Step #2 - Create a CustomDateAdapter, that will be responsible for parsing the date during run-time

// customDateAdapter.ts
import { Injectable } from '@angular/core';
import { MomentDateAdapter } from '@angular/material-moment-adapter';
import * as moment from 'moment';
import { DateTimeService } from './date-time.service';

@Injectable()
export class CustomDateAdapter extends MomentDateAdapter
{
  constructor(private _dateTimeService: DateTimeService)
  {
    super('en-US'); // set default locale
  }

  public format(date: moment.Moment, displayFormat: string): string
  {
    const locale = this._dateTimeService.getLocale();
    const format = this._dateTimeService.getFormat();

    return date.locale(locale).format(format);
  }
}

请注意:CustomDateAdapter"是一个常规类,而不是一个组件.虽然我们正在注入一个服务到这个类.为此,我们需要将 @Injectable() 装饰器添加到CustomDateAdapter",并在 app.module.ts 中进行一些轻微的更改.

Please Notice: That "CustomDateAdapter" is a regular class, and not a component. Although we are injecting a service to this class. To achieve this we need to add the @Injectable() decorator to the "CustomDateAdapter", and make some light changes in the app.module.ts.

// app.module.ts
import { DateAdapter, MatNativeDateModule } from '@angular/material';
import { MatMomentDateModule } from '@angular/material-moment-adapter'
import { CustomDateAdapter } from './<some-path>/customDateAdapter';

@NgModule({
  imports:
  [
    MatNativeDateModule,
    MatMomentDateModule
  ],
  providers:
  [
    CustomDateAdapter, // so we could inject services to 'CustomDateAdapter'
    { provide: DateAdapter, useClass: CustomDateAdapter }, // Parse MatDatePicker Format
  ]
})
export class AppModule { /* ... */ }

附注
请注意,问题中的代码(来自demo.component.ts")不再相关.

P.S
Please notice that the code from the question (from the "demo.component.ts") isn't relevant any more.

Stackblitz 演示

这篇关于如何在运行时更改 Angular Material Datepicker 格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆