1

Somehow I can't apply a custom date format to my material Datepicker. I have also tried implementing it the same way as it's proposed at Material Datepicker

Due I think this is overly complicated and wasn't working( ERROR Error: Datepicker: Value must be either a date object recognized by the DateAdapter or an ISO 8601 string. Instead got: 1525125600000)

I tried to use this reference implementation from this stack answer. Resulting in the same error. It is obviously converting the date to an timestamp, so the formatting string seems to be applied as expected.... Also I'm wondering why the implementation of angular results in the same error (with a different timestamp because it's using the current date as start-position). The problem it, that i have absolutely no idea where to look for the mistake anymore

This is my .component.ts:

import {Component, Input, forwardRef} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {MatDatepickerInputEvent} from '@angular/material/datepicker';
import {default as _rollupMoment} from 'moment';
import * as _moment from 'moment';

const DATEMOMENT = _rollupMoment || _moment;

@Component({
  selector: 'custom-date-picker',
  templateUrl: 'app/components/datepicker/datepicker.component.html',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => DatePickerComponent),
      multi: true
    }
  ]
})
export class DatePickerComponent implements ControlValueAccessor {

  private tecDateValue: string = '28.05.1994';
  @Input() public dateFormat: string = 'dd.MM.yyyy';
  @Input() public placeholder: string;

  @Input()
  public get dateValue() {
    return DATEMOMENT(this.tecDateValue, this.dateFormat);
  }

  public set dateValue(val) {
    this.tecDateValue = DATEMOMENT(val).format(this.dateFormat);
    this.propagateChange(this.tecDateValue);
  }

  public addEvent(type: string, event: MatDatepickerInputEvent<Date>) {
    console.log(event.value);
    this.dateValue = DATEMOMENT(event.value, this.dateFormat);
  }

  public writeValue(value: any) {
    if (value !== undefined) {
      this.dateValue = DATEMOMENT(value, this.dateFormat);
    }
  }

  private propagateChange = (val: any) => {
  };

  public registerOnChange(fn: any) {
    this.propagateChange = fn;
  }

  public registerOnTouched() {
  }
}
Johannes M
  • 65
  • 1
  • 9

2 Answers2

0

maybe you can set Locale on your constructor.. it works for me

constructor(private adapter: DateAdapter<any>) {
    this.adapter.setLocale('es');
}

hope it was usefull :)

chinaski
  • 116
  • 1
  • 7
0

I couldn'd find a propper solution for this problem. The way I obviated the problem was by just hiding the date pickers input field and use a stock material instead and then partse the input. Altough it's not a clean solution, it's at least working.

Johannes M
  • 65
  • 1
  • 9