角度材料datepicker格式输入

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

我正在尝试格式化Angular材质datepicker的输入。

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

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

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

javascript angular momentjs angular2-template material
1个回答
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"}}
© www.soinside.com 2019 - 2024. All rights reserved.