我正在尝试格式化Angular材质datepicker的输入。
例如,当用户键入2,3,2018并按Enter键时,日期将设置为:2/3/2018。问题是,datepicker以id的形式获取值,例如,对于2/3/2018,它使用id 1517608800000
。我可以像这样使用momentjs格式化组件中的值:
this.value.format('MM/DD/YYYY')
它正确格式化代码,但它不会将其应用回输入。在视图中,值与ngModel
绑定。
也许你可以使用管道:
import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
@Pipe({
name: 'datex'
})
export class DatexPipe implements PipeTransform {
transform(value: any, format: string = ''): string {
// Try and parse the passed value.
const momentDate = moment(value);
// If moment didn't understand the value, return it unformatted.
if (!momentDate.isValid()) {
return value;
}
// Otherwise, return the date formatted as requested.
return momentDate.format(format);
}
}
并将其应用于模板:
{{data | datex: "DD/MM/YYYY HH:mm:ss"}}