提交表格后,角材料数据贴纸的格式不同

时间:2017-09-08 14:29:16

标签: angular angular-material2

当我选择数据时,它会以

之类的格式填充输入

DD/MM/YYYY

但我需要通过表单发送数据, 当我在我的组件上执行console.log时

datapicker.component.ts

onFindAWhip(form: NgForm){
    const value = form.value;
    console.log(value);
 }

我得到像

这样的完整日期
Thu Sep 28 2017 00:00:00 GMT+0100 (GMT Daylight Time)
  

我是否必须重新格式化?

已经在我的DateAdapter中完成了,我已经尝试从这里获取它,但我只是得到错误

import { NativeDateAdapter }  from '@angular/material';

export class MyDateAdapter extends NativeDateAdapter {
   format(date: Date, displayFormat: Object): string {

      let day = date.getDate();
      let month = date.getMonth();
      let year = date.getFullYear();

      if (displayFormat == "input") {


          let pickupData = date.toDateString();
          let pickupDataArray = pickupData.split(" ");
          let yearPicked = pickupDataArray[3]; 

          const without = pickupData.substring(0, pickupData.length-4);

          return without + '     '+yearPicked ;

       } else if (displayFormat == "input-home") {
          return this._to2digit(day) + '/' + this._to2digit(month) +'/'+ year;
       }

       else{
        return date.toDateString();
      }
   }

   private _to2digit(n: number) {
       return ('00' + n).slice(-2);
   }

}

datapicker.html

<span class="calendar-to">
        <button md-raised-button (click)="pickupTo.open()" class="search--icon"></button>
        <input  [mdDatepicker]="pickupTo"
                placeholder="DD/MM/YYYY"
                name="date_to"
                ngModel>
        <md-datepicker touchUi="true" #pickupTo></md-datepicker>
    </span>

1 个答案:

答案 0 :(得分:1)

这是因为ngModel是一个DateTime,并包含所有那些信息。如果您只想要DD/MM/YYYY,则必须在component.ts中处理它。您实际上只需在组件中使用Angular's DatePipe即可快速轻松地为您执行此操作。

导入管道:

import { DatePipe } from '@angular/common'

构建访问权限:

constructor( private datePipe: DatePipe ) { }

在方法中使用:

onFindAWhip(form: NgForm){
    const value = form.value;
    console.log(this.datePipe.transform(value, 'MM/dd/y'));
 }