我正在研究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'
最好的方法是构建自定义日期适配器(这是一项服务)。当您使用JavaScript Date
对象作为基础日期格式时,只需扩展NativeDateAdapter
中提供的@angular/material/core
。您只需要重写两种方法:parse
和format
。前者从格式中获取Date
对象,而后者从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);
}
// 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;
}
}