Angular Date Time Picker

repository·master·Indexed 41 days ago

https://github.com/danielmoncada/date-time-picker

An implementation-agnostic Angular component library for responsive date and time pickers. It supports native JS Dates, Unix timestamps, Day.js, and Moment.js via adapters. The library integrates with Angular Forms via the owlDateTime directive and requires @angular/cdk for overlay rendering. Current version supports Angular 22.

Tokens
15.5K
Snippets
36
Records
48
Agent score
99%

What's inside Angular Date Time Picker

  1. Configure localization and DateTime formats

    master

    To customize the language and date/time formatting for the picker, use the following injection tokens:

    • OWL_DATE_TIME_LOCALE: Defines the locale for different languages.
    • OWL_DATE_TIME_FORMATS: Defines the specific date and time formats used by the picker.
  2. Choose a date implementation for the picker

    master

    The picker is implementation-agnostic. You must provide a module that matches your data type:

    • Native JS Date: Use OwlNativeDateTimeModule.
    • Unix Timestamp (milliseconds): Use OwlUnixTimestampDateTimeModule.
    • DayJs: Install @danielmoncada/angular-datetime-picker-dayjs-adapter and use OwlDayJsDateTimeModule.
    • MomentJs: Install @danielmoncada/angular-datetime-picker-moment-adapter and use OwlMomentDateTimeModule.
  3. Install peer dependency `@angular/cdk`

    master

    The picker requires @angular/cdk as a peer dependency to provide the overlay used for rendering.

    Important: You must include the CDK overlay styles in your project. If you are not already using Angular Material, add the following to your styles:

    @use '@angular/cdk/overlay-prebuilt.css';
  4. Initialize OwlDateTimeModule in your Angular application

    master

    Import OwlDateTimeModule and a date implementation module (like OwlNativeDateTimeModule) into your @NgModule to enable the picker functionality.

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { MyTestApp } from './my-test-app';
    import { OwlDateTimeModule, OwlNativeDateTimeModule } from '@danielmoncada/angular-datetime-picker';
    
    @NgModule({
        imports: [BrowserModule, OwlDateTimeModule, OwlNativeDateTimeModule],
        declarations: [MyTestApp],
        bootstrap: [MyTestApp],
    })
    export class MyTestAppModule {}
  5. Configure styles for the Date/Time Picker

    master

    The picker uses CDK overlays. If you are not using Angular Material, you must manually include the CDK overlay styles and the picker styles. You can do this in your styles.scss or via the styles array in angular.json.

    // In styles.scss
    @use '@angular/cdk/overlay-prebuilt.css';
    @use '@danielmoncada/angular-datetime-picker/assets/style/picker.min.css';
    // In angular.json
    "styles": [
        "node_modules/@angular/cdk/overlay-prebuilt.css",
        "node_modules/@danielmoncada/angular-datetime-picker/assets/style/picker.min.css",
        "src/styles.scss"
    ]
  6. Install @danielmoncada/angular-datetime-picker

    master

    To use the Angular Date/Time Picker, install the package and its required peer dependency, @angular/cdk.

    Note: The current version supports Angular 22. If you are using an older version of Angular, refer to the version compatibility mapping in the documentation to select the appropriate package version.

    npm install @danielmoncada/angular-datetime-picker --save
    npm install @angular/cdk --save
  7. How OwlDateTimeComponent and OwlDateTimeInputDirective work together

    master

    The OwlDateTimeComponent acts as a controller that must be associated with an input directive (OwlDateTimeInputDirective). The component manages the overlay (popup or dialog), while the directive (applied to an <input> element) handles the value binding and formatting.

    Key constraints:

    • An OwlDateTimeComponent can only be associated with a single input directive.
    • The component's open() method requires an associated input to function.
    • The component's selected and selecteds properties are synchronized with the input's value via the registerInput method.
  8. Implement a custom DateTimeAdapter

    master

    To use a specific date library (like Moment.js, Luxon, or native JS Date) with the picker, you must extend the DateTimeAdapter<T> abstract class. You need to implement methods for extracting date components (year, month, day, etc.), performing arithmetic (addCalendarDays, etc.), and formatting/parsing.

    // Abstract signature of the class you must extend
    export abstract class DateTimeAdapter<T> {
      // ... abstract methods to implement ...
      abstract getYear(date: T): number;
      abstract getMonth(date: T): number;
      abstract getDay(date: T): number;
      abstract getDate(date: T): number;
      abstract getHours(date: T): number;
      abstract getMinutes(date: T): number;
      abstract getSeconds(date: T): number;
      abstract getTime(date: T): number;
      abstract getNumDaysInMonth(date: T): number;
      abstract differenceInCalendarDays(dateLeft: T, dateRight: T): number;
      abstract getYearName(date: T): string;
      abstract getMonthNames(style: 'long' | 'short' | 'narrow'): string[];
      abstract getDayOfWeekNames(style: 'long' | 'short' | 'narrow'): string[];
      abstract getDateNames(): string[];
      abstract toIso8601(date: T): string;
      abstract isEqual(dateLeft: T, dateRight: T): boolean;
      abstract isSameDay(dateLeft: T, dateRight: T): boolean;
      abstract isValid(date: T): boolean;
      abstract invalid(): T;
      abstract isDateInstance(obj: any): boolean;
      abstract addCalendarYears(date: T, amount: number): T;
      abstract addCalendarMonths(date: T, amount: number): T;
      abstract addCalendarDays(date: T, amount: number): T;
      abstract setHours(date: T, amount: number): T;
      abstract setMinutes(date: T, amount: number): T;
      abstract setSeconds(date: T, amount: number): T;
      abstract createDate(year: number, month: number, date: number): T;
      abstract createDate(year: number, month: number, date: number, hours: number, minutes: number, seconds: number): T;
      abstract clone(date: T): T;
      abstract now(): T;
      abstract format(date: T, displayFormat: any): string;
      abstract parse(value: any, parseFormat: any): T | null;
    }
  9. Configure PickerType, PickerMode, and SelectMode

    master

    The picker's behavior is governed by three primary type definitions:

    • PickerType: Defines what the picker displays.

      • 'both': Displays both date and time.
      • 'calendar': Displays only the date.
      • 'timer': Displays only the time.
    • PickerMode: Defines how the picker is presented in the UI.

      • 'popup': Opens in a popup overlay.
      • 'dialog': Opens in a modal dialog.
      • 'inline': Rendered directly within the layout.
    • SelectMode: Defines how many values can be selected.

      • 'single': Single date/time selection.
      • 'range': A range of two dates.
      • 'rangeFrom': Selecting the start of a range.
      • 'rangeTo': Selecting the end of a range.
  10. Use the `owlDateTime` directive for Angular Forms integration

    master

    The owlDateTime directive is applied to an <input> element to integrate the date-time picker with Angular's Reactive or Template-driven forms. It implements ControlValueAccessor and Validator, allowing it to work seamlessly with ngModel or formControlName.

    To use it, apply the owlDateTime attribute to your input and pass the associated OwlDateTimeComponent instance to it.

    <input [owlDateTime="picker"] [(ngModel)]="myDate" />
    <owl-date-time #picker></owl-date-time>
  11. Connect a picker to an input and a trigger

    master

    To use the picker, connect an <input> to an <owl-date-time> component using the [owlDateTime] directive. You can trigger the picker via the input itself or through a separate element (like a span or icon) using the [owlDateTimeTrigger] directive.

    <!-- Trigger via the input itself -->
    <input [owlDateTime="dt1"] [owlDateTimeTrigger="dt1"] placeholder="Date Time" /> 
    <owl-date-time #dt1></owl-date-time>
    
    <!-- Trigger via a separate element (e.g., an icon) -->
    <input [owlDateTime="dt2"] placeholder="Date Time" />
    <span [owlDateTimeTrigger="dt2"><i class="fa fa-calendar"></i></span>
    <owl-date-time #dt2></owl-date-time>
  12. Configure the default scroll strategy via OWL_DTPICKER_SCROLL_STRATEGY

    master

    You can provide a custom global scroll strategy for the date picker using the OWL_DTPICKER_SCROLL_STRATEGY injection token. This determines how the background scrolls when the picker overlay is open. By default, the library provides a factory that uses the Angular CDK BlockScrollStrategy to block scrolling.

    import { OWL_DTPICKER_SCROLL_STRATEGY } from '@danielmoncada/angular-datetime-picker';
    
    // In your @NgModule or Component providers:
    providers: [
      {
        provide: OWL_DTPICKER_SCROLL_STRATEGY,
        useFactory: (overlay: Overlay) => () => overlay.scrollStrategies().block(),
        deps: [Overlay]
      }
    ]