2

I have created a custom directive to add features to the existing matDatePicker control. This directive has an Input attribute called format which gives date format at run time. I have provided the MyDateAdapter as mention in Angular 2 Material 2 datepicker date format

My question is; how I can set the Input format value to the datepicker date format at run time as an when my value of format get changed.

My Directive:

@Directive({
  selector: '[dateFormat]',
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: DateFormatDirective,
      multi: true
    },
    {
      provide: DateAdapter, useClass: MyDateAdapter
    },
    {
      provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS
    }
  ]
})
export class DateFormatDirective {
  @Input('dateFormat') format: string;
}

MyDateAdapter class and MY_DATE_FORMATS constant refer

1 Answer 1

3

After looking into material datepicker and NativeDateAdapter source code I found the solution for above issue.

modify MyDateAdapter

import {TranslateService} from '@ngx-translate/core';
export class MyDateAdapter  extends NativeDateAdapter {
    format:string;
    constructor( private datepipe: DatePipe,  platform: Platform,translate: TranslateService) {
        super('en', platform);
        translate.get('dateFormat').subscribe(ts =>{ 
             this.format=dateFormat;
        });
    }
    format(date: Date, displayFormat: Object): string {
        if (displayFormat === 'input') {
            return this.datepipe.transform(date, this.format);
        } else {
            return date.toDateString();
        }
    }
}

Add factory function:

export function createDateAdapterLoader (dp: DatePipe,  platform: Platform,ts: TranslateService) {
  return new MyDateAdapter(dp,  platform, ts);
}

modify Directive:

    import {TranslateService} from '@ngx-translate/core';
    import {DatePipe} from '@angular/common';
    import {Platform} from '@angular/cdk/platform';
    @Directive({
      selector: '[dateFormat]',
      providers: [
        {
          provide: NG_VALIDATORS,
          useExisting: DateFormatDirective,
          multi: true
        },
        {
          provide: DateAdapter,
          useFactory: createDateAdapterLoader,
          deps: [DatePipe, Platform ,TranslateService]
        },
        {
          provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS
        }
      ]
    })
    export class DateFormatDirective {
      @Input('dateFormat') format: string;
    }

You need to provide DatePipe in AppModule.

This is called Factory provider to create the dependent value dynamically!! refer

To get format value from i18n file you can use any internationalization (i18n) library, eg:@ngx-translate

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.