如何将Date数组转为ngx-mydatepicker的IMyDate数组赋值给disableDates
Convert Date[] to IMyDate[] for ngx-mydatepicker's disableDates
Got it, let's fix this conversion issue for ngx-mydatepicker's disableDates option! The key here is understanding that IMyDate expects a simple object with year, month, and day properties (important note: month is 1-based here, unlike JavaScript's native Date which uses 0-based months).
Here's how to adjust your code to make this work:
Updated TypeScript Code
import { INgxMyDpOptions, IMyDate } from 'ngx-mydatepicker'; // Normally fetched from your API invalidJsDates: Date[] = [new Date("2018-05-09"), new Date("2018-05-29")]; // Helper function to convert Date objects to IMyDate format convertToIMyDate(dates: Date[]): IMyDate[] { return dates.map(date => { return { year: date.getFullYear(), month: date.getMonth() + 1, // Add 1 to shift from 0-based to 1-based month day: date.getDate() }; }); } myOptions: INgxMyDpOptions = { dateFormat: 'mm/dd/yyyy', disableDates: this.convertToIMyDate(this.invalidJsDates) // Use converted array here };
Important Tips:
- Month Adjustment: Don't skip adding 1 to
date.getMonth()! JavaScript returns months from 0 (January) to 11 (December), but ngx-mydatepicker expects months starting at 1. - Async API Scenario: If your
invalidJsDatescomes from an async API call, updatemyOptionsafter the data loads to ensure the disabled dates are applied correctly. Example:this.yourApiService.getInvalidDates().then(dates => { this.invalidJsDates = dates; // Update options without overwriting existing settings this.myOptions = { ...this.myOptions, disableDates: this.convertToIMyDate(this.invalidJsDates) }; });
Your HTML Code Stays the Same
<div class="input-group"> <input class="form-control" style="float:none" placeholder="Select a date" ngx-mydatepicker name="mydate" [(ngModel)]="model" [options]="myOptions" #dp="ngx-mydatepicker"/> <span class="input-group-btn"> <button type="button" class="btn btn-default" (click)="dp.clearDate()"> <i class="glyphicon glyphicon-remove"></i> Clear </button> <button type="button" class="btn btn-default" (click)="dp.toggleCalendar()"> <i class="glyphicon glyphicon-calendar"></i>Toggle </button> </span> </div>
This conversion will correctly map your native JavaScript Date objects to the IMyDate format ngx-mydatepicker expects, so those dates will be properly disabled in the calendar.
内容的提问来源于stack exchange,提问作者FirstDivision
相关产品推荐
相关产品推荐

