ngbdatepicker动态禁用日期对象

时间:2019-04-25 17:55:10

标签: angular ngb-datepicker

我正在尝试仅禁用用户选择的日期。经过多次试验,我能够这样做,但是它禁用了所有日历。我希望它仅禁用选定的日期。

ng-bootstrap上的当前资料仅将天数设为数字,而不是对象:

https://ng-bootstrap.github.io/#/components/datepicker/overview

打字稿代码:

import {Component, Input, Output, EventEmitter} from '@angular/core';
import {NgbDate, NgbCalendar} from '@ng-bootstrap/ng-bootstrap';
import { stringify } from '@angular/compiler/src/util';

@Component({
  selector: 'ngbd-datepicker-range',
  templateUrl: './datepicker-range.html',
export class NgbdDatepickerRange {    

  hoveredDate: NgbDate;
  fromDate: NgbDate;
  toDate: NgbDate;
  DiffDate:number;
  startDate;
  endDate;

 disabeledDays: NgbDate [] = new Array(); //this is array of date objects, which i want to disable



  constructor(calendar: NgbCalendar) {
    this.fromDate = calendar.getToday();
    this.toDate = calendar.getNext(calendar.getToday(), 'd', 1);      
    this.DiffDate=this.calcDaysDiff();     
  }

 isDisabled = (date: NgbDate) => {
    for (var i =0; i < this.disabeledDays.length;i++){
      date= this.disabeledDays[i]; 
      console.log(date);   
    } return date;
  } //this is function for disabling the dates

 onDateSelection(date: NgbDate) {
    console.log('onDateSelection:', date);
    if (!this.fromDate && !this.toDate) {
      this.fromDate = date;
      this.DiffDate = this.calcDaysDiff();
      this.FromDateEvent.emit(date);


    } else if (this.fromDate && !this.toDate && date.after(this.fromDate)) {
      this.toDate = date;
      this.DiffDate = this.calcDaysDiff();
      this.EndDateEvent.emit(date);


    } else {
      this.toDate = null;
      this.fromDate = date;

      this.FromDateEvent.emit(date);

      this.disabeledDays.push(date); //pushing a date to the array of disabled dates
    }
  }

}

HTML:

ngb-datepicker [markDisabled]="isDisabled" #dp (select)="onDateSelection($event)" [displayMonths]="2" [dayTemplate]="t" outsideDays="hidden"
>
</ngb-datepicker>



<ng-template #t let-date let-focused="focused" class="container">
  <span class="custom-day"
        [class.focused]="focused"
        [class.range]="isRange(date)"
        [class.faded]="isHovered(date) || isInside(date)"
        (mouseenter)="hoveredDate = date"
        (mouseleave)="hoveredDate = null">
    {{ date.day }}
  </span>
</ng-template>

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您将需要对isDisabled属性进行一些更改。简而言之,您应该返回一个布尔值(truefalse),而不是原始代码中声明的NgbDate日期对象。 .from()实际上是NgbDate API的一部分,它从NgbDateStruct创建了一个新的日期对象。

isDisabled = (date: NgbDateStruct, current: {month: number, year: number})=> {
  return this.disabledDates.find(x => NgbDate.from(x).equals(date))? true: false;
}

disabledDates代表NgbDate对象的数组,该对象应在日期选择器本身上禁用。

disabledDates: NgbDateStruct[] = [ 
  {year: 2019, month:4, day:10},
  {year: 2019, month:4, day:12},
  {year: 2019, month:4, day:14},
];

这里是demo,请检查一下以了解其工作原理。