来自 Ng2 Bootstrap 的日期选择器在无法读取 getFullYear() 时不断抛出错误

Date Picker from Ng2 Bootstrap keep throwing error on unable to read getFullYear()

我在尝试使用 ng2-bootstrap 中的日期选择器禁用日期时遇到了一些问题。在我的 app.module.ts 中,我这样导入了库:

import {DatepickerModule} from 'ng2-bootstrap';
@NgModule({
imports: [

    DatepickerModule.forRoot()
],

在我的 html:

<div class="col-sm-6 form-group has-feedback" [ngClass]="displayFeedBackCss('testDte')">
        <label for="testDte">TEST DATE<span class="text-danger">*</span></label>
        <datepicker
            [(ngModel)]="testDte"
            [showWeeks]="true"
            [minDate]="minDate"
            [dateDisabled]="disabledDate"
            [onlyCurrentMonth]=true
        ></datepicker>
    </div>

在我的 ts 文件中:

disabledDate:any;
date:Date;

ngOnInit(): void {
this.date = new Date();
this.disabledDate = [
  {dt: this.date.getDate()-1, mode: 'day'},
  {dt: this.date.getDate()-2, mode: 'day'}
];
}

但是,我一直在控制台中收到此错误消息:

EXCEPTION: Error in ./e class e - inline template:25:6 caused by: Cannot read properties of undefined (reading 'getFullYear')
e.handleError @ vendor.2b9f55e0bbcf755a8964.js:30
vendor.2b9f55e0bbcf755a8964.js:30 ORIGINAL EXCEPTION: Cannot read properties of undefined (reading 'getFullYear')

我什至尝试将日期硬编码为“2021-12-16”和“16/12/2021”。但是,相同的错误消息仍然显示。有什么想法吗?

谢谢!

看来问题是 datesDisabled 配置需要是根据 the docs 的日期数组。而且你好像用过dateDisabled(缺少's')

因此您的模板代码应更改为

       <datepicker
            [(ngModel)]="testDte"
            [showWeeks]="true"
            [minDate]="minDate"
HERE >>>>   [datesDisabled]="disabledDate"
            [onlyCurrentMonth]=true
        ></datepicker>

并且您的组件代码也需要根据 docs 进行调整,以便可以正确解释传递到 datesDisabled 配置中的内容。

来自文档的示例:

  disabledDates = [
    new Date('2020-02-05'),
    new Date('2020-02-09')
  ];

请注意ng2-bootstrap has been deprecated. I suggest moving to ngx-bootstrap

install ngx-bootstrap --save

并参考The Fabio's .

以下是旧版本。

dateDisabled 选项需要

dateDisabled (?Array<{date:Date, mode:string}>) - array of disabled dates if mode is day, or years, etc.

ngOnInit(): void {
    this.date = new Date();
    let disabledStartDate = new Date();
    disabledStartDate.setDate(this.date.getDate()-1);
    let disabledEndDate = new Date();
    disabledEndDate.setDate(this.date.getDate()-2);
    this.disabledDate = [
        {date:disabledStartDate , mode: 'day'},
        {date:disabledEndDate , mode: 'day'}
    ];
}