Skip to content

Instantly share code, notes, and snippets.

@Onas182
Last active June 22, 2021 07:50
Show Gist options
  • Save Onas182/8a146f8cbe3afe35f32a4454833f9368 to your computer and use it in GitHub Desktop.
Save Onas182/8a146f8cbe3afe35f32a4454833f9368 to your computer and use it in GitHub Desktop.
Location Customization (Change Language) in @coachcare/datepicker

Material DatePicker by CoachCare

Fork of the official Material Datepicker for Angular v6 with timepicker support.

The datepicker allows users to enter a date either through text input, or by choosing a date from the calendar.
It is made up of several components and directives that work together.

Further documentation can be found at the official docs: https://material.angular.io/components/datepicker/overview

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

The mat-datepicker has the following input parameters:

  • startAt: start Date/Moment, otherwise the current selected value
  • type: date | datetime | time output type and available views. default: date
  • startView: clock | month | year | years initial view to load. default: month
  • clockStep: interval to use in the clock view. default: 1
  • twelveHour: whether to use 12 or 24 hrs format. default: false
  • touchUi: calendar UI mode. default: true (recommended)
  • disabled: whether the datepicker pop-up should be disabled
  • matDatepicker: whether the datepicker is connected to a date type one

and the input[matDatepicker] has the output:

  • dateChange: Emits when a change event is fired on this <input>.
  • dateInput: Emits when a input event is fired on this <input>.

Installation

As usual run yarn add @coachcare/datepicker or npm install @coachcare/datepicker.
This module requires moment and moment-timezome for the MomentDateAdapter.

Now add the modules to your Angular Module:

import { MatDatepickerModule, MatMomentDateModule } from '@coachcare/datepicker';

@NgModule({
  imports: [
    MatDatepickerModule,
    MatMomentDateModule,
    ...
  ],
  ...
})
export class AppModule {}

Note that the MatDatepickerModule can be loaded into feature modules,
but it requires the providers given by MatMomentDateModule,
so it's recommended to be imported in your root Module.

Styling

This module supports the Angular Material prebuilt themes that can be included in angular.json:

"styles": [
  "node_modules/@coachcare/datepicker/prebuilt-themes/indigo-pink.css",
  ...
],

available themes are deeppurple-amber, indigo-pink, pink-bluegrey and purple-green.

You can use your customized Material Theme as usual:

@import '~@coachcare/datepicker/theming';

@include mat-datepicker-theme($theme);

Also, the primary color can be customized with CSS variables. The required ones are:

body {
  --bg-dialog: white;
  --primary: rgba(73, 200, 242, 1);
  --primary-contrast: #fff;
  --primary-a60: rgba(73, 200, 242, 0.6);
  --primary-a80: rgba(73, 200, 242, 0.8);
}

Location Customization (Change Language)

You have to run yarn add moment or npm install moment

and yarn add moment-timezone or npm install moment-timezone

Then you have to create a service, you can named it for example datepicker-esp.ts

Should be like this file

Then create other file named for example moment.es.ts

Should be like this file

Then in the app.module.ts use below:

import { NgModule, LOCALE_ID } from '@angular/core';
import { DatepickerEsp } from './services/datepicker-esp';


import * as moment from 'moment';
// moment.es.ts created previously
import './services/moment.es'; 
moment.locale('es');

...

providers: [
  { provide: LOCALE_ID, useValue: 'es' },
  { provide: MatDatepickerIntl, useClass: DatepickerEsp }
  ],
  

Date Formats Customization

This fork uses an extended set of DateFormats,

You can create a file named for example moment-date-formats.ts and should be like this file

And you should put in the app.module.ts

import { NgModule, LOCALE_ID } from '@angular/core';

import { DateAdapter, MAT_DATE_FORMATS, MatDatepickerIntl, 
  MatDatepickerModule, MatMomentDateModule, MomentDateAdapter} from '@coachcare/datepicker';

// moment-date-formats.ts created previously
import { MAT_MOMENT_DATE_FORMATS } from './services/moment-date-formats';


...

  providers: [
    
    { provide: DateAdapter, useClass: MomentDateAdapter, deps: [LOCALE_ID] },
    { provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS },
  ],

For information about Localized formats go to next link

Usage Examples

DateTime picker (year, month, date and clock views)

<mat-datepicker type="datetime" clockStep="5" #pickerStart></mat-datepicker>

DateTime picker (starting on the clock view)

<mat-datepicker type="datetime" startView="clock" #startPicker></mat-datepicker>

Time picker (clock views, with 5 minutes jump)

<mat-datepicker type="time" clockStep="5" #timeStart></mat-datepicker>

Contribute

Feedback and suggestions are welcome, also gratitude demonstrations :) https://www.paypal.me/mateotp

Enjoy!

// locale configuration
// locale : Spanish [es]
import { Injectable } from '@angular/core';
import { MatDatepickerIntl } from '@coachcare/datepicker';
import * as moment from 'moment';
import './moment.es';
/** Datepicker data that requires internationalization. */
@Injectable({ providedIn: 'root' })
export class DatepickerEsp extends MatDatepickerIntl {
constructor() {
super();
moment.locale('es');
}
/** A label for the calendar popup (used by screen readers). */
calendarLabel = 'Calendario';
/** A label for the button used to open the calendar popup (used by screen readers). */
openCalendarLabel = 'Abrir calendario';
/** A label for the previous month button (used by screen readers). */
prevMonthLabel = 'Mes anterior';
/** A label for the next month button (used by screen readers). */
nextMonthLabel = 'Mes siguiente';
/** A label for the previous year button (used by screen readers). */
prevYearLabel = 'Año anterior';
/** A label for the next year button (used by screen readers). */
nextYearLabel = 'Año siguiente';
/** A label for the 'AM' button (used by screen readers). */
setToAMLabel = 'Fijar hora a AM';
/** A label for the 'PM' button (used by screen readers). */
setToPMLabel = 'Fijar hora a PM';
/** A label for the 'switch to minute view' button (used by screen readers). */
switchToMinuteViewLabel = 'Cambiar a vista de minutos';
/** A label for the 'switch to hour view' button (used by screen readers). */
switchToHourViewLabel = 'Cambiar a vista de horas';
/** A label for the 'switch to month view' button (used by screen readers). */
switchToMonthViewLabel = 'Cambiar a vista del mes';
/** A label for the 'switch to year view' button (used by screen readers). */
switchToYearViewLabel = 'Cambiar a vista de año';
/** A label for the 'switch to years view' button (used by screen readers). */
switchToYearsViewLabel = 'Cambiar a vista de años';
/** Text for the 'submit' button. */
buttonSubmitText = 'Ok';
/** A label for the 'submit' button (used by screen readers). */
buttonSubmitLabel = 'Elegir la fecha seleccionada';
/** Text for the 'cancel' button. */
buttonCancelText = 'Cancelar';
/** A label for the 'cancel' button (used by screen readers). */
buttonCancelLabel = 'Cancelar la selección de fecha';
}
// moment.js locale configuration
// locale : Spanish [es]
import * as momentNs from 'moment-timezone';
const moment = momentNs;
const monthsRegex = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i;
const monthsShortRegex = /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i;
const monthsParse = [
/^ene/i,
/^feb/i,
/^mar/i,
/^abr/i,
/^may/i,
/^jun/i,
/^jul/i,
/^ago/i,
/^sep/i,
/^oct/i,
/^nov/i,
/^dic/i
];
const es = {
months: 'Enero Febrero Marzo Abril Mayo Junio Julio Agosto Septiembre Octubre Noviembre Diciembre'.split(
' '
),
monthsShort: 'Ene Feb Mar Abr May Jun Jul Ago Sep Oct Nov Dic'.split(' '),
monthsRegex: new RegExp(monthsRegex.source + monthsShortRegex.source, 'i'),
monthsShortRegex: monthsRegex,
monthsStrictRegex: monthsRegex,
monthsShortStrictRegex: monthsShortRegex,
monthsParse: monthsParse,
longMonthsParse: monthsParse,
shortMonthsParse: monthsParse,
weekdays: 'Domingo Lunes Martes Miércoles Jueves Viernes Sábado'.split(' '),
weekdaysShort: 'Dom Lun Mar Mié Jue Vie Sáb'.split(' '),
weekdaysMin: 'Do Lu Ma Mi Ju Vi Sá'.split(' '),
weekdaysParseExact: true,
longDateFormat: {
LT: 'h:mm a',
LTS: 'h:mm:ss a',
L: 'DD/MM/YYYY',
l: 'D/M/YYYY',
LL: 'MMMM D, YYYY',
ll: 'MMM D, YYYY',
LLL: 'MMMM D [de] YYYY, [a las] h:mm a',
lll: 'MMM D [de] YYYY [a las] h:mm a',
LLLL: 'dddd, MMMM D [de] YYYY [a las] h:mm a',
llll: 'ddd, MMM D [de] YYYY [a las] h:mm a'
},
calendar: {
sameDay: function (): string {
// tslint:disable-next-line:no-invalid-this
return '[hoy a la' + (Number(this.hours()) !== 1 ? 's' : '') + '] LT';
},
nextDay: function (): string {
// tslint:disable-next-line:no-invalid-this
return '[mañana a la' + (Number(this.hours()) !== 1 ? 's' : '') + '] LT';
},
nextWeek: function (): string {
// tslint:disable-next-line:no-invalid-this
return 'dddd [a la' + (Number(this.hours()) !== 1 ? 's' : '') + '] LT';
},
lastDay: function (): string {
// tslint:disable-next-line:no-invalid-this
return '[ayer a la' + (Number(this.hours()) !== 1 ? 's' : '') + '] LT';
},
lastWeek: function (): string {
// tslint:disable-next-line:no-invalid-this
return '[el] dddd [pasado a la' + (Number(this.hours()) !== 1 ? 's' : '') + '] LT';
},
sameElse: 'L',
hours: () => '' // lint workaround
},
relativeTime: {
future: 'en %s',
past: 'hace %s',
ss: 'unos pocos segundos',
s: 'unos segundos',
m: 'un minuto',
mm: '%d minutos',
h: 'una hora',
hh: '%d horas',
d: 'un día',
dd: '%d días',
M: 'un mes',
MM: '%d meses',
y: 'un año',
yy: '%d años'
},
dayOfMonthOrdinalParse: /\d{1,2}º/,
ordinal: function (n: number): string {
return `${n}º`;
},
week: {
dow: 0, // CCR: Sunday as first day of the week.
doy: 4 // The week that contains Jan 4th is the first week of the year.
}
};
// ('es') IMPORTANT means spanish
moment.defineLocale('es', es);
moment.locale('es');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment