角度材料datepicker格式输入

时间:2018-03-16 09:53:33

标签: javascript angular momentjs angular2-template material

我正在尝试从Angular素材日期选择器中格式化输入

例如,当用户键入 2,3,2018 并按输入时,日期设置为: 2/3/2018 。问题是,datepicker以id的形式获取值,例如对于 2/3/2018 ,它使用id 1517608800000。我可以使用像这样格式化组件中的值:

this.value.format('MM/DD/YYYY')

它正确格式化代码,但它不会将其应用回输入。在视图中,值与ngModel绑定。

1 个答案:

答案 0 :(得分:0)

也许你可以使用烟斗:

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"}}