Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CustomeDateAdapter in Angular Material 6

I have implemented a CustomDateAdapter as described here: https://medium.com/@esanjiv/working-with-custom-dateadapter-for-angular-material-2-datepicker-76d4446277dc

Now, I am doing the Angular Material 6 migration and I get the following error

core.js:1598 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'TRIDENT' of undefined
TypeError: Cannot read property 'TRIDENT' of undefined
at CustomDateAdapter.NativeDateAdapter [as constructor] (core.es5.js:792)
at new CustomDateAdapter (custom-date-adapter.ts:21)
at _createClass (core.js:9262)
...

core.es5.js line 792 is this:

_this.useUtcForDisplay = !platform.TRIDENT;

It seems that the platform is undefined.

I noticed that the constructor of the NativeDateAdapter has changed in Material 6, it also requires a platform as input.

constructor(matDateLocale: string, platform: Platform);

What I am missing? How can I implement a CustomDateAdapter in Angular Material 6?

like image 213
René Winkler Avatar asked Dec 11 '22 06:12

René Winkler


2 Answers

I had the same problem. Here is my fix.

// in your shared or main.module.ts
// … other imports
import {Platform, PlatformModule} from '@angular/cdk/platform';

@NgModule({
  imports: [
    // …
    PlatformModule
  ],
  exports: [
    // …
    PlatformModule
  ],
  providers: [
    {provide: DateAdapter, useClass: YourCustomDateAdapter, deps: [MAT_DATE_LOCALE, Platform]},
  ]
 });
 export class SharedModule {
}

And you haven't override the YourCustomDateAdapter's constructor.

like image 109
Londeren Avatar answered Dec 12 '22 18:12

Londeren


I solved this problem by instantiating in my code a Platform object

export class CustomDateAdapter extends NativeDateAdapter {

  constructor(matDateLocale: string) {
    super(matDateLocale, new Platform());
  }

...

}

Another option is to provide it with a factory

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [
    {
      provide: Platform,
      useFactory: platformProviderFactory,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

export function platformProviderFactory() {
  return () => new Platform();
}
like image 38
Rafa Garés Avatar answered Dec 12 '22 18:12

Rafa Garés