角度日期选择器自定义值在Angular中获取错误

问题描述 投票:0回答:1

我正在研究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代码。这是我想要的格式2020年7月7日

    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)
        });     
    }

获取错误为:

错误TypeError:无法读取未定义的属性'getDate'

angular angular8 mat mat-datepicker
1个回答
0
投票

最好的方法是构建自定义日期适配器(这是一项服务)。当您使用JavaScript Date对象作为基础日期格式时,只需扩展NativeDateAdapter中提供的@angular/material/core。您只需要重写两种方法:parseformat。前者从格式中获取Date对象,而后者从Date对象中获取字符串对象(例如问题文本中提供的formatDate函数)。

构建自定义日期适配器后,只需将其放入令牌AppModuleDateAdapter提供程序数组中即可:

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);
    }

    // maybe you don't want to parse anything else here
    // so just replace to: return null;
    return value ? new Date(Date.parse(value)) : 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;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.