0

下面是我的日期范围组件 Html

    <mat-label>Enter a date range</mat-label>
    <mat-date-range-input
      [rangePicker]="picker"
      [dateFilter]="rangeFilter"
      formGroupName="dateRange"
    >
      <input
        matStartDate
        placeholder="Start date"
        formControlName="start"
        autocomplete="off"
      />
      <input
        matEndDate
        placeholder="End date"
        formControlName="end"
        autocomplete="off"
      />
    </mat-date-range-input>
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-date-range-picker #picker></mat-date-range-picker>
  </mat-form-field>

对于 [dateFilter]="rangeFilter" 我在我的组件中添加了以下函数

 rangeFilter(date: Date): boolean {
    return date.getDate() > 20;
  }

我的 package.json 文件是

{
  "name": "front-end",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~12.2.0",
    "@angular/cdk": "^12.2.6",
    "@angular/common": "~12.2.0",
    "@angular/compiler": "~12.2.0",
    "@angular/core": "~12.2.0",
    "@angular/forms": "~12.2.0",
    "@angular/material": "^12.2.6",
    "@angular/platform-browser": "~12.2.0",
    "@angular/platform-browser-dynamic": "~12.2.0",
    "@angular/router": "~12.2.0",
    "rxjs": "~6.6.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.2.6",
    "@angular/cli": "~12.2.6",
    "@angular/compiler-cli": "~12.2.0",
    "@types/jasmine": "~3.8.0",
    "@types/node": "^12.11.1",
    "jasmine-core": "~3.8.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "typescript": "~4.3.5"
  }
}

但我得到的错误是'(date: Date) => boolean' is notassignable to type 'DateFilterFn'

我尽我所能。但是得到这个错误。需要您的宝贵建议。

4

2 回答 2

1

根据MatDateRangeInput dateFilterInput 属性,

@Input()
dateFilter: DateFilterFn<D>

DateFilterFn

type DateFilterFn = (date: D | null) => boolean;

因此更改rangeFilter' 方法签名如下:

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

rangeFilter: DateFilterFn<Date> = (date: Date | null) => {
  // Implementation
  return date?.getDate() > 20;
};
于 2021-09-25T03:51:28.920 回答
0

如果要过滤掉范围,则结果必须是布尔值,而不是日期。您正在尝试返回一个运行时转换错误的日期:

尝试以下方法以过滤出未来 20 天内的天数:

rangeFilter(date: Date): boolean {
    let currentDate: Date = new Date();
    let includeDatesWithinNextTwentyDays: boolean = date.valueOf() < (currentDate.valueOf() + 20*60*60*1000*24);
    return includeDatesWithinNextTwentyDays;
}

这应该为您在日期选择器中显示的每个日期提供一个布尔值。false 表示日期显示为灰色,true 表示日期可选。

于 2021-09-25T01:44:26.540 回答