Angular Material 17 No provider for DateAdapter in Standalone Component

887 Views Asked by At

I have a nx project with angular 17 app and try to use a the angular material date picker with material 17.0.4. But I get the

NullInjectorError: No provider for DateAdapter!

Error. The components are standalone components and so there is no app.module file.

The component

@Component({
  selector: 'my-component',
  standalone: true,
  imports: [
    MatFormFieldModule,
    MatInputModule,
    MatDatepickerModule,
    FormsModule,
    MatIconModule,
    MatButtonModule,
    MatNativeDateModule,
    NgIf
  ],
  providers: [MatNativeDateModule],
  templateUrl: './edit-booking.component.html',
  styleUrl: './edit-booking.component.css',
})
export class EditBookingComponent implements OnInit {}

I also tried to import the providers in the app.config.ts

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(appRoutes),
    provideAnimations(),
    provideHttpClient(withInterceptors([authInterceptor])),
    {provide: LOCALE_ID, useValue: 'de-AT'},
    importProvidersFrom(MatNativeDateModule)

  ],
};

but then I get this error:

Cannot read properties of undefined (reading 'liveCollection')

Thanks a lot!

1

There are 1 best solutions below

0
ferhado On

Try this configration:

// locale-config.ts

import {LOCALE_ID, Provider} from '@angular/core';
import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material/core';

import localeDe from '@angular/common/locales/de';
import localeDeExtra from '@angular/common/locales/extra/de';

import {registerLocaleData} from '@angular/common';
registerLocaleData(localeDe, localeDeExtra);

export function provideLocaleConfig(): Provider[] {
  return [
    {
      provide: LOCALE_ID,
      useValue: 'de-AT',
    },
    {
      provide: DateAdapter,
      useClass: NativeDateAdapter,
      deps: [MAT_DATE_LOCALE],
    },
  ];
}


// app.config.ts
export const appConfig: ApplicationConfig = {
  providers: [
    // ...
    provideLocaleConfig(),
    // ...
  ],
};

and remove MatNativeDateModule from your component