Search code examples
angulardependency-injectiondatepickerdate-rangeowl-date-time

How to dynamically change Datepicker date time format?


Since the format for @danielmoncada/angular-datetime-picker datepicker is being provided via Angular DI, we need to utilize this approach and dynamically provide the formats.

This is what the dates From and To look like now:

enter image description here

This is what I wanted to achieve: when we have month view selected - we dynamically change the datepicker formats to the desired:

enter image description here


Solution

  • First we need to create a format provider service, which we will then inject into the datepicker component:

    @Injectable()
    export class DatepickerFormatsProvider {
      private currentFormats: OwlDateTimeFormats;
    
      constructor() {
        this.currentFormats = DAYS_VIEW_FORMATS;
      }
    
      setFormats(formats: OwlDateTimeFormats) {
        this.currentFormats = formats;
      }
    
      getFormats(): OwlDateTimeFormats {
        return this.currentFormats;
      }
    }
    

    Inject in into the component and use useFactory to get the format.

    @Component({
      selector: 'datepicker',
      templateUrl: 'datepicker.component.html',
      providers: [
        {
          provide: OWL_DATE_TIME_FORMATS,
          useFactory: (datepickerFormatsProvider: DatepickerFormatsProvider) => datepickerFormatsProvider.getFormats(),
          deps: [DatepickerFormatsProvider],
        },
        DatepickerFormatsProvider
      ]
    })
    export class DatepickerComponent implements OnInit {
    

    In same component in OnInit Hook you can overwrite the default provided value:

      ngOnInit(): void {
        if (this.selectionMode === 'month') {
          this.datepickerFormatsProvider.setFormats(MONTH_VIEW_FORMATS);
        } else {
          this.datepickerFormatsProvider.setFormats(DAYS_VIEW_FORMATS);
        }
      }
    

    If we need to dynamically change the date-format of the datepicker - it only works in OnInit hook. We need to re-render the component and trigger OnInit E.g. with use of *ngIf and async pipe on datepicker selector in parent component.