【问题标题】:Angular / Material / Datepicker - No provider found for DateAdapterAngular / Material / Datepicker - 找不到 DateAdapter 的提供者
【发布时间】:2019-01-12 21:40:31
【问题描述】:

我有一个问题:angular / material / datepicker

我有一个虚拟项目可以正常使用以下文件:

/src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatStepperModule, MatInputModule, MatButtonModule, MatNativeDateModule } from '@angular/material';
import { MatDatepickerModule } from '@angular/material/datepicker';

import { AppComponent } from './app.component';
import { StepperComponent } from './components/stepper/stepper.component';
import { DatepickerComponent } from './components/datepicker/datepicker.component';

@NgModule({
    declarations: [
        AppComponent,
        StepperComponent,
        DatepickerComponent,
    ],
    imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        BrowserAnimationsModule,
        MatStepperModule,
        MatInputModule,
        MatButtonModule,
        MatNativeDateModule,
        MatDatepickerModule,
    ],
    providers: [],
    bootstrap: [ AppComponent ]
})
export class AppModule { }

/src/app/components/datepicker/datepicker.component.html

<mat-form-field>
    <input matInput [matDatepicker]="picker" placeholder="Choose a date">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

这是我正在检查的 API:

https://material.angular.io/components/datepicker/api

我想知道,为什么如果我在文件上注释:MatNativeDateModule 的导入:app.module.ts 我进入浏览器,错误:

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."

API 部分,他们没有提到那个模块。

他们在Overview 部分提到了该模块,但没有提供太多细节。

你能帮我解决这个问题吗?这有时看起来很模糊。

谢谢!

【问题讨论】:

  • 在您的导入中交换 MatNativeDateModuleMatDatepickerModule 的顺序
  • 什么?,为什么?,你能解释一下你的意思吗?
  • 我猜测 MatNativeDateModule 需要在 MatDatepickerModule 之后构建,这可能是导致问题的原因。核心路由模块和动画模块具有类似的效果。您的导入顺序很重要,示例按此顺序排列!
  • 但我的问题不是关于订单,而是为什么如果我删除该导入,我会收到该错误?,谢谢!
  • 抱歉,我看错了。模块MatNativeDateModule 有一个名为DateAdapter 的服务,它需要由父模块提供 才能注入。这就是provider/@Injector标签进来的地方。因为你没有导入MatNativeDateModule,所以没有模块来提供InjectableDateAdapter,因此会抛出错误。

标签: angular typescript datepicker material-design angular6


【解决方案1】:

这个想法是让开发人员可以随意选择他们想要的日期提供程序,没有任何限制,因此他们没有在 overview 下而不是在 API 下提及它,因为API 仅适用于 Angular Material Design 的核心 API,可让您控制和访问特定的材料组件。

matNativeDateModule 不是通过对时间进行解析作为整体开发的模块,只是告诉matDatePicker 嘿,当您使用日期对象时,请使用本机 JavaScript 日期对象。也许您不想使用它并使用您自己的日期对象或 JavaScript 日期库,例如 momentjs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 2018-01-09
    • 2020-07-01
    • 2021-06-09
    • 2021-01-06
    • 2019-12-05
    相关资源
    最近更新 更多