0

我正在研究 Mat 日期选择器自定义值。这是我正在尝试的代码

      <div class="form-group" *ngIf="selectVal.value == 'Date'">
                <mat-form-field>
                <input matInput [matDatepicker]="picker" (dateChange)="formatDate(dateValue.value)" #dateValue  formControlName="assumptionValueInDatetime" class="form-control" placeholder="Choose a date" >
                    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
                    <mat-datepicker #picker></mat-datepicker>
                </mat-form-field>
            </div>

这是我的 ts 代码。这是我想要的格式 07-JUL-2020

    formatDate(value) {
        const months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
        let formatDate = ('0' + value.getDate()).slice(-2) + "-" + months[value.getMonth()] + "-" + (value.getFullYear());
        return formatDate;
    }

这是我的有效载荷的样子:

    initassumpationForm() {
        this.assumptionDesignForm = this.fb.group({
            assumptionValueInDatetime: this.formatDate(this.assumptionValueInDatetime)
        });     
    }

得到错误为:

错误类型错误:无法读取未定义的属性“getDate”

4

1 回答 1

0

最好的方法是构建一个自定义日期适配器(它是一项服务)。当您使用 JavaScriptDate对象作为基础日期格式时,您只需扩展NativeDateAdapter提供的 in@angular/material/core并覆盖两个方法:parseformat. 前者Date从您的字符串格式中获取一个对象(例如:01-MAR-2020),后者从一个对象中获取一个字符串对象Date(就像formatDate问题文本中提供的函数一样)。

在构建您的自定义本机日期适配器类之后,只需在您的AppModule使用令牌中提供它DateAdapter

import {DateAdapter} from '@angular/material/core';
...

@NgModule({
  ...
  providers: [{provide: DateAdapter, useClass: CustomNativeDateAdapter}]
  ...
})
export class AppModule {}

关于CustomNativeDateAdapter课程,在您的情况下,它将类似于:

import { Injectable } from '@angular/core';
import { NativeDateAdapter } from '@angular/material/core';

@Injectable()
export class CustomNativeDateAdapter extends NativeDateAdapter {
  months: string[] = [ 'JAN', 'FEB', 'MAR', 'APR',  'MAY', 
    'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC' ];

  monthsObj: { [key: string]: number } = { JAN: 0, FEB: 1, MAR: 2, APR: 3, 
    MAY: 4, JUN: 5, JUL: 6, AUG: 7, SEP: 8, OCT: 9, NOV: 10, DEC: 11 };

  parse(value: any): Date | null {
    if (typeof value == 'number') {
      return new Date(value);
    }

    const dateRegex: RegExp = /^(0|1)[1-9]-[A-Z]{3}-(1|2)[0-9]{3}$/;
    if (typeof value == 'string' && dateRegex.test(value)) {
      const dateSplit = value.split('-');
      return new Date(+dateSplit[2], this.monthsObj[dateSplit[1]],
        +dateSplit[0], 12, 0, 0, 0);
    }

    return null;
  }

  format(date: Date, displayFormat: Object): string {
    if (!this.isValid(date)) {
      throw Error('NativeDateAdapter: Cannot format invalid date.');
    }

    let formatDate = ('0' + date.getDate()).slice(-2) +
      '-' + this.months[date.getMonth()] + '-' + date.getFullYear();
    return formatDate;
  }
}
于 2020-03-26T09:41:03.293 回答