角度8:NullInjectorError:没有MatCalendar提供程序

时间:2019-11-15 06:15:04

标签: angular typescript angular8

我有以下代码,并收到错误消息。我该如何解决?我正在使用Angular日期模块创建日期选择器,

  

NullInjectorError:StaticInjectorError(AppModule)[MonthDayDatepickerComponent-> MatCalendar]:     StaticInjectorError(平台:核心)[MonthDayDatepickerComponent-> MatCalendar]:       NullInjectorError:MatCalendar没有提供程序!

已经做了

import { MatDatepickerModule } from '@angular/material/datepicker';

并再次在imports[

import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  Inject,
  OnDestroy
} from '@angular/core';
import {MatCalendar} from '@angular/material/datepicker';
import {DateAdapter, MAT_DATE_FORMATS, MatDateFormats, MAT_DATE_LOCALE} from '@angular/material/core';
import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from '@angular/material-moment-adapter';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import * as _moment from 'moment';

const moment =  _moment;
import {FormControl} from '@angular/forms';

export const MONTH_DAY_DATE_FORMATS = {
  parse: {
    dateInput: 'MM/DD',
  },
  display: {
    dateInput: 'MM/DD',
    monthYearLabel: 'MMM',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

@Component({
  selector: 'app-month-day-datepicker',
  templateUrl: './month-day-datepicker.component.html',
  styleUrls: ['./month-day-datepicker.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [{
    provide: DateAdapter,
    useClass: MomentDateAdapter,
    deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
  }, { provide: MAT_DATE_FORMATS, useValue: MONTH_DAY_DATE_FORMATS }]
})
export class MonthDayDatepickerComponent<D> implements OnDestroy {
  private _destroyed = new Subject<void>();

  constructor(
    private _calendar: MatCalendar<D>, private _dateAdapter: DateAdapter<D>,
    @Inject(MAT_DATE_FORMATS) private _dateFormats: MatDateFormats, cdr: ChangeDetectorRef) {
    _calendar.stateChanges
      .pipe(takeUntil(this._destroyed))
      .subscribe(() => cdr.markForCheck());
  }

  ngOnDestroy() {
    this._destroyed.next();
    this._destroyed.complete();
  }

  get periodLabel() {
    return this._dateAdapter
      .format(this._calendar.activeDate, this._dateFormats.display.monthYearLabel)
      .toLocaleUpperCase();
  }

  previousClicked(mode: any) {
    this._calendar.activeDate = this._dateAdapter.addCalendarMonths(this._calendar.activeDate, -1);
  }

  nextClicked(mode: any) {
    this._calendar.activeDate = this._dateAdapter.addCalendarMonths(this._calendar.activeDate, 1);
  }
}

3 个答案:

答案 0 :(得分:0)

我想您还没有加入模块MatDatepickerModulesource

对于Angular Material中的每个特征,您需要导入相应的模块。

答案 1 :(得分:0)

您需要导入app.module.ts并写入您的导入文件,希望对您有所帮助。

答案 2 :(得分:0)

我认为您的导入文件存在问题。在本文中,有一个小的指南可以处理Angular中的材料。

Set Up an Angular 8 Project with Material and NGXS

因为我在使用Angular项目之前曾使用过UI的角度材质。我总是从Array ( [0] => 2019-11-15 [1] => 2019-12-15 [2] => 2020-01-15 [3] => 2020-02-15 [4] => 2020-03-15 ) 导入材料模块。