In contrast on what has been said previously by some colleagues, you should NOT put MatDatepickerModule in prodivers array unless you have a good reason for it.
As a reminder (https://angular.io/guide/providers), and as it is well explained in the official documentation: A provider is an instruction to the Dependency Injection system on how to obtain a value for a dependency. Most of the time, these dependencies are services that you create and provide. In addition to this, providers are available to all the classes in the application which is not i guess, the purpose of MatDatepickerModule ! (since you should use it just in some few components)
So all what you need is to follow of course the examples well documented in the Angular official website (https://material.angular.io/components/datepicker/overview)
But before to check the solution, let’s have a look at the self-explanatory error message:
ERROR Error: MatDatepicker: No provider found for DateAdapter. You must import one of the following modules at your application root: MatNativeDateModule, ....
It is not because the error talks initially about provider, that you just need to inject the staff in provider. Continue reading the full error…
Just one word about DateAdapter: DateAdapter is a class which adapts an object to be usable as a date by cdk-based components that work with dates. This DateAdapter needs to use some native functions from MatNativeDateModule
The suggested solution is:
In your app.module.ts import both MatDatepickerModule and MatNativeDateModule
...
import {MatDatepickerModule} from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';
...
@NgModule({
imports: [MatDatepickerModule, MatNativeDateModule],
})
export class MyApp {}
Juste giving more info on this.
I have a separate Web component project to publish components on private npm (verdaccio).
Here is the DatePicker Component details :
// DatePickerModule import { NgModule } from '@angular/core'; import {DatePickerComponent} from './date-picker/date-picker.component'; import {HttpClientModule} from '@angular/common/http'; import {FormsModule} from '@angular/forms'; import {CommonModule} from '@angular/common'; import {TranslateModule} from '@ngx-translate/core'; import {MatDatepickerModule, MatFormFieldModule, MatInputModule} from '@angular/material'; @NgModule({ imports: [ MatFormFieldModule, MatInputModule, MatDatepickerModule, HttpClientModule, CommonModule, FormsModule, TranslateModule ], exports: [DatePickerComponent], declarations: [DatePickerComponent], providers: [ ] }) export class DatePickerModule { }
The HTML template:
<div class="row middle-xs" ngClass="{{topClass}}"> <!-- ************************************************************************************************ --> <!-- ******************************************** PREFIXE ******************************************* --> <!-- ************************************************************************************************ --> <div *ngIf="label || iconClass" ngClass="{{classPrefix}}"> <div *ngIf="iconClass" class="inline-block"> <i ngClass="{{iconClass}}" aria-hidden="true"></i><span *ngIf="withSemiColon && !label"> :</span> </div> <div *ngIf="label" class="inline-block"> {{label | translate}}<span *ngIf="withSemiColon"> :</span> </div> </div> <!-- ************************************************************************************************ --> <!-- ******************************************** DATE PICKER *************************************** --> <!-- ************************************************************************************************ --> <!--class="clean-space"--> <div ngClass="{{valueClass}}"> <mat-form-field class="auto-width" [ngClass]="isConsultation ? 'no-icon no-top-border' : 'container-input-date '"> <input matInput [matDatepicker]="pickerDebut" class="consultation" [disabled]="isConsultation" [(ngModel)]="theDate" ngModelOptions="{timezone:'UTC/GMT'}"> <mat-datepicker-toggle matSuffix [for]="pickerDebut" [disabled]="isConsultation"></mat-datepicker-toggle> <mat-datepicker #pickerDebut ></mat-datepicker> </mat-form-field> </div> </div>
the component.ts
import {Component, Input, forwardRef, ViewEncapsulation} from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl, } from '@angular/forms'; export function validateDateInputFormat(c: FormControl): any { // Error content in case input date format is not valid let err = { formatError: { given: c.value, acceptedFormat: 'dd/MM/yyyy' } }; // Control logiq // return c.value == null ? null : (String(c.value).match(date_regexp)) ? null : err; return null; } @Component({ selector: 'app-date-picker', templateUrl: './date-picker.component.html', styleUrls: ['./date-picker.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => DatePickerComponent), multi: true }, { provide: NG_VALIDATORS, useValue: validateDateInputFormat, multi: true } ], encapsulation: ViewEncapsulation.Emulated }) export class DatePickerComponent implements ControlValueAccessor { @Input() label: string; @Input() isConsultation: boolean; @Input() withSemiColon: boolean; @Input() topClass: string; @Input() prefixClass: string; @Input() valueClass: string; @Input() classPrefix: string; @Input() iconClass: string; private _theDate: string; constructor() { } propagateChange = (_: any) => {}; onTouched: any = () => { }; writeValue(obj: any): void { if (obj) { this._theDate = obj; } } registerOnChange(fn: any): void { this.propagateChange = fn; } registerOnTouched(fn: any): void { this.onTouched = fn; } get theDate() { return this._theDate; } set theDate(val) { this._theDate = val; this.propagateChange(val); } }
Now in my App, I import date picker module and provide a DateAdapter and LOCALE
import { BrowserModule } from '@angular/platform-browser'; import { NgModule} from '@angular/core'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import {RouterModule} from '@angular/router'; import {AppRoutingModule} from './app.routing'; import 'hammerjs'; import { DateAdapter } from '@angular/material'; import {HTTP_INTERCEPTORS, HttpClient, HttpClientModule} from '@angular/common/http'; import {AuthGuard} from './shared/guard/AuthGuard'; import {JwtInterceptor} from './shared/interceptor/jwt.interceptor'; import {ToastyModule} from 'ng2-toasty'; import {TranslateHttpLoader} from '@ngx-translate/http-loader'; import {TranslateLoader, TranslateModule} from '@ngx-translate/core'; import {SharedModule} from './shared/shared.module'; import {MAT_DATE_LOCALE} from '@angular/material'; import {MatDialogModule} from '@angular/material'; import {CustomDateAdapter} from './shared/internationalization/custom-date-adapter'; export function createTranslateLoader(http: HttpClient) { return new TranslateHttpLoader(http, 'assets/i18n/', '.json'); } @NgModule({ declarations: [ AppComponent ], imports: [ SharedModule, AppRoutingModule, BrowserModule, BrowserAnimationsModule, HttpClientModule, RouterModule, ToastyModule.forRoot(), TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: (createTranslateLoader), deps: [HttpClient] } }), APP_MODULES_HERE ], exports: [ MatDialogModule ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, {provide: MAT_DATE_LOCALE, useValue: 'fr-FR'}, {provide: DateAdapter, useClass: CustomDateAdapter}, APP_SERVICES_HERE ], bootstrap: [AppComponent] }) export class AppModule { }
shared modules imports all Material stuff, and my DatePickerModule
import {CommonModule} from '@angular/common'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {NgModule} from '@angular/core'; import { TranslateModule } from '@ngx-translate/core'; import {ChartsModule} from 'ng2-charts'; import {CdkTableModule} from '@angular/cdk/table'; import { MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatGridListModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressBarModule, MatProgressSpinnerModule, MatRadioModule, MatRippleModule, MatSelectModule, MatSidenavModule, MatSliderModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatTabsModule, MatToolbarModule, MatTooltipModule } from '@angular/material'; import {RouterModule} from '@angular/router'; import {DatePickerModule} from 'nsi.datepicker/date-picker.module'; @NgModule({ imports: [ ChartsModule, CdkTableModule, MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatGridListModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressBarModule, MatProgressSpinnerModule, MatRadioModule, MatRippleModule, MatSelectModule, MatSidenavModule, MatSliderModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatTabsModule, MatToolbarModule, MatTooltipModule, CommonModule, FormsModule, ReactiveFormsModule, RouterModule, DatePickerModule, ], declarations: [ ... ], exports: [ ChartsModule, CdkTableModule, MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatGridListModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressBarModule, MatProgressSpinnerModule, MatRadioModule, MatRippleModule, MatSelectModule, MatSidenavModule, MatSliderModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatTabsModule, MatToolbarModule, MatTooltipModule, CommonModule, RouterModule, FormsModule, ReactiveFormsModule, TranslateModule, DatePickerModule, ] }) export class SharedModule { }
Hope it helps
While using the Angular material Datepicker in the application, you may face an issue saying:
“ERROR Error: MatDatepicker: No provider found for DateAdapter. You must import one of the following modules at your application root: MatNativeDateModule, MatMomentDateModule, or provide a custom implementation.”
Solution using Mat Native Date Adapter :
Make sure to import the MatNativeDateModule
as already mentioned in the error message.
Open the app.module.ts file and update the AppModule as shown below:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatNativeDateModule } from '@angular/material/core';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatDatepickerModule,
MatFormFieldModule,
MatNativeDateModule, // <- Added MatNativeDateModule Here
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
Solution using Moment Date Adapter
If you want to use the MatMomentDateModule
DateAdapter then you need to install the @angular/material-moment-adapter and moment library by executing the below command:
npm install moment
npm install @angular/material-moment-adapter
Otherwise, you will see an error saying: Cannot find module ‘@angular/material-moment-adapter‘ or its corresponding type declarations.
After installation is completed, update the AppModule as shown below:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatMomentDateModule } from '@angular/material-moment-adapter';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
HttpClientModule,
BrowserAnimationsModule,
MatDatepickerModule,
MatFormFieldModule,
MatMomentDateModule, // <- Added MatMomentDateModule
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
After adding any of the above adapter the issue will be resolved.
- | Sign In
- Ask Question
Error: «MatDatepicker: No provider found for DateAdapter
I am creating Angular Material Datepicker .
<mat-form-field> <mat-label>Select Date</mat-label> <input matInput [matDatepicker]="dt"> <mat-datepicker-toggle matSuffix [for]="dt"></mat-datepicker-toggle> <mat-datepicker #dt></mat-datepicker> </mat-form-field>
But getting following error.
Error: «MatDatepicker: No provider found for DateAdapter. You must import one of the following modules at your application root: MatNativeDateModule, MatMomentDateModule, or provide a custom implementation.»
Mohit
Replied on June 25, 2020
You are missing
import { MatNativeDateModule } from ‘@angular/material/core’;
For Datepicker, make sure you have following settings.
app.module.ts
import { MatInputModule } from ‘@angular/material/input’;
import { MatDatepickerModule } from ‘@angular/material/datepicker’;
import { MatNativeDateModule } from ‘@angular/material/core’;
@NgModule({
imports: [
——
MatInputModule,
MatDatepickerModule,
MatNativeDateModule
],
——
})
export class AppModule { }
Write Answer
Issue
I’m trying to use the Datepicker component in Angular Material. Here is my HTML code:
<input matInput [matDatepicker]="picker" placeholder="Choose a date" disabled>
<mat-datepicker #picker disabled="false"></mat-datepicker>
However, it’s not working for me and I’m getting the following error:
Error: MatDatepicker: No provider found for DateAdapter.
The error message tells me that I need to import MatNativeDateModule as well as MatDatepickerModule but I have done that. Here is my import code below from app.module.ts:
import {
MatFormFieldModule,
MatMenuModule,
MatCheckboxModule,
MatIconModule,
MatDatepickerModule,
MatNativeDateModule
} from '@angular/material';
Is there anything else I’m missing?
Solution
You need to import both MatDatepickerModule
and MatNativeDateModule
under imports and add MatDatepickerModule
under providers
imports: [
MatDatepickerModule,
MatNativeDateModule
],
providers: [
MatDatepickerModule,
],
Answered By — Sajeetharan