0
votes

Is it possible to auto-format the date (moment) in the input of the datepicker from angular material ?

My use case is let the user type a date "DDMMYYYY" in the input and if it's a valid date for the "fr-FR" locale, to format the same way as when you use directly the calendar, so "DD/MM/YYYY". Example : 03052018 > 03/05/2018

I want to do it for all the datepicker of my application, so i would like to know if it can be achieve by extend MomentDateAdapter or something similar ? Actually i do it manually with (dateChange) event and binding const formatedValue = moment(value, 'DDMMYYYY', 'fr-FR'); to the input

Thanks in advance !

ps : Datepicker from angular material documentation

1
you could use the pipe for itDemonFilip
can you give an example of a pipe doing it ?WizardPC

1 Answers

0
votes

Finally i used a directive :

import { Directive, ElementRef, HostListener } from '@angular/core';
import * as moment from 'moment';

@Directive({
  selector: '[appFormatDate]'
})
export class FormatDateDirective {
  constructor(private el: ElementRef) {}

  @HostListener('blur')
  onBlur() {
    const inputValue = this.el.nativeElement.value;
    console.log(inputValue);

    if (inputValue !== '') {
      this.formatDate(inputValue);
    }
  }

  formatDate(value: string) {
    const momentDate = moment(value, ['DDMMYYYY', 'D MMMM YYYY'], 'fr-FR'); // Ex : [01012018, 1 janvier 2018]
    const formatedValue = momentDate.isValid() ? momentDate.format('DD/MM/YYYY') : value;
    console.log(formatedValue);
    this.el.nativeElement.value = formatedValue;
  }
}