Restricting Dates in Angular 2 Date Picker

I encountered an issue while attempting to disable specific dates in a date picker. Here is my custom date picker written in TypeScript:

import { DateFormatter } from './ng2-bootstrap/date-formatter';
import { DatePickerComponent } from './ng2-bootstrap/datepicker.component';
import * as moment from 'moment-timezone';

@Component({
    selector: '[acn-datepicker-popup]',
    templateUrl: './datepicker-popup.component.html',
    inputs: [],
    host: {}
})
export class DatepickerPopupComponent implements OnInit {
    @Input() datepickerDirective: any;
    @Input() minDate: moment.Moment;
    @Input() maxYears: number;
    @Input() alignRight: boolean = false;
    @Input() disabledDates: string;

    private dateFormat: string = 'DD/MM/YYYY';
    private earliestDate: string = '01/01/1970';
    
    datePickerCmp: DatePickerComponent;
    datepickerFormControl: FormControl;
    selectedDate: moment.Moment;
    dateFormatter: DateFormatter = new DateFormatter();
    
    constructor(private _datePickerCmp: DatePickerComponent, @Inject('datepickerFormControl') private _datepickerFormControl: FormControl) {
        this.datePickerCmp = _datePickerCmp;
        this.datepickerFormControl = _datepickerFormControl;
        if (this.datepickerFormControl.value && this.dateFormatter.isValid(this.datepickerFormControl.value, this.dateFormat)) {
            this.selectedDate = moment(this.datepickerFormControl.value, this.dateFormat);
        }    
    }

    ngOnInit() {
        var splits = this.disabledDates.toString().split(";");
        for(let i = 0; i < splits.length; i++){
            console.log("Dates" + splits[i]);
        }
    }

Here is the HTML for my date picker component:

<div class="col-sm-6 form-group has-feedback">
        <label for="testDte">TEST DATE<span class="text-danger">*</span></label>
        <div class="input-group" [(datepicker-popup)]="bookingModel.controls.testDte" [disabledDates]="bkDatesListStr">
            <input type="text" [formControl]="bookingModel.controls.testDte" class="form-control"  maxlength="10" style="border-right:transparent">
            <span class="input-group-btn" align="right">
                <button class="btn btn-square btn-white-primary form-control" type="button"><i class="fa fa-calendar"></i></button>
            </span>
        </div>
    </div>

I have successfully retrieved the dates to be disabled in the ngOnInit() method. The splits variable now contains the list of dates that should be greyed out in the date picker. However, I am unsure of how to actually disable these dates in the date picker. Any suggestions would be greatly appreciated!

Thank you!

Answer №1

Here is a simple example demonstrating how to disable specific dates.

Start by adding the Material Design theme to your Angular application by running the following command:

ng add @angular/material

In your TypeScript file:

import { Component } from '@angular/core';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'my-app';
  
    myHolidayDates = [
                    new Date("12/1/2020"),
                    new Date("12/20/2020"),
                    new Date("12/17/2020"),
                    new Date("12/25/2020"),
                    new Date("12/4/2020"),
                    new Date("12/7/2020"),
                    new Date("12/12/2020"),
                    new Date("12/11/2020"),
                    new Date("12/26/2020"),
                    new Date("12/25/2020")
                ];
  
    myHolidayFilter = (d: Date): boolean => {
        const time = d.getTime();
        return !this.myHolidayDates.find(x => x.getTime() == time);
    }
}

In your view file, implement the following code for the input element with a datepicker:

<h1>Angular Material Disable specific dates</h1>
     
<mat-form-field>
  <input matInput [matDatepicker]="picker" [matDatepickerFilter]="myHolidayFilter" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker ></mat-datepicker>
</mat-form-field>

Feel free to test this solution in your application.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Integrating a local library with Angular: A comprehensive guide

As I was developing an Angular application, I had the idea to create a library containing reusable components for future projects. To achieve this, I set up a separate Angular workspace where I created a library project. I utilized the automatically genera ...

Troubleshooting issues encountered while sending HttpClient Get Requests from Angular Front-End to Node.js Back-End

I am encountering an issue where I keep getting the error message "Cannot GET /" on my local host URL when attempting to send a HttpClient get request from my Angular front-end to my Node.js back-end endpoint. Despite the fact that my back-end endpoint suc ...

When transitioning from the current step to the previous step in the mat-stepper component, how can we emphasize the horizontal line that separates them?

screenshot of my progress I have progressed from A3 to A2 step, but I need to add a horizontal line between them. How can I achieve this and is it possible to do so using CSS styles? ...

Exploring Angular: Enhancing Routing through GET Requests

I've been working on a cutting-edge application that combines an Angular 2 frontend with a powerful Java backend. An exciting feature of this application is a dynamic form, consisting of various search criteria. Upon submission, I execute an http get ...

Angular script error when running 'npm run' on select computers causing Unix command issues for some users but not all

Recently, I've encountered a puzzling issue at my workplace that has been difficult to diagnose. We utilize scripts in npm within the Angular framework to launch a local server instance. Strangely enough, some of my colleagues' computers are thro ...

How should one properly format an array of objects with elements that are different types of variations?

I am currently developing a versatile sorting module using TypeScript. This module will take in an array of data objects, along with a list of keys to sort by. Once the sorting process is complete, the array will be sorted based on the specified keys. To ...

The cucumber_report.json file will not update to reflect the most recent test steps

I have encountered an issue with the cucumber_reporter.json file not overwriting under the reports/html folder in my framework. To address this, I made changes to the cucumberOpts option within my config.ts file. By modifying the format setting to "json:./ ...

Reactive Forms are being loaded dynamically without waiting for the completion of the http call

I've been working on loading dynamic field forms based on input from an HTTP service. The service provides metadata about which fields to load, including the name and type of each field. Therefore, I need to dynamically build the formGroup in ngOnInit ...

"Unlocking the Power of Monaco Editor: A Guide to Fetching CompletionItems from Your

Currently, I have integrated the fantastic monaco editor into my Angular 8 app for editing formulas. Everything is working fine, but now I need the list of suggestions (CompletionItems) to update dynamically. I have utilized the ngx-monaco-editor module a ...

Retrieving the value that is not currently selected in a mat-select component

In my mat-table, there is a mat-select component displayed like this: <mat-select multiple placeholder="{{element.name}}" [(value)]="selectedCol" (selectionChange)="selectionChange($event)" [disabled]="!selection.isSelected(element.id)"> & ...

What is the best way to incorporate resources from a different location in an Angular project?

I am facing an issue with the deployment time of my server as I am using @angular/localize to support three languages in my application. Despite all locales sharing the same assets, they are being downloaded and deployed individually for each one. To addr ...

Learning to integrate Socket.io into your FeathersJS service

I've been working on integrating Socket.io into my Feathersjs/Angular application and have successfully set up communication between the front and back ends. While I understand that the configuration in app.js is responsible for establishing server c ...

Protecting scripts using bypassSecurityTrustStyle in Angular

Is there a way to remove all script tags from a string while preserving the style? Consider this code snippet where we sanitize the style of a string: getSanitized(s: string) { const safeStyle: any = this.sanitizer.bypassSecurityTrustStyle(s); re ...

Utilize mapping to object and preserve type inference

I am currently developing a function that utilizes a map function to map objects. interface Dictionary<T> { [key: string]: T; } function objectMap<TValue, TResult>( obj: Dictionary<TValue>, valSelector: (val: TValue) => TResult ...

Unable to modify the text value of the input field

I am currently learning how to code in React, so please forgive me if my question seems basic. I am attempting to change the text of an Input element based on the value of the filtered variable, like this: const contactContext = useContext(ContactContext); ...

Enforce boundaries by constraining the marker within a specified polygon on a leaflet map

Currently, I am utilizing a leaflet map to track the user's location. The map includes a marker for the user and a polygon shape. My goal is to ensure that the user marker always stays within the boundaries of the defined polygon. In case the user mov ...

In Angular, a function becomes undefined when passed to a class in a model, but functions properly when directly called

I am in the process of developing a class that includes a function designed to initiate a recursive loop every 5 seconds. This loop will utilize the http.request library to check specific server settings. When the setting matches the predefined criteria pa ...

Using React JS to Sort an Array Based on a Specific String

Here I am again, this time dealing with reactjs. I have a json object containing two "rows", labeled as Description and ubication. My goal is to filter the array based on the Description field. How can I achieve this? The description is in text format, f ...

The issue with importing fonts in CSS causing an error is encountered when utilizing an exported Angular library

I have a components library for Angular that relies on line-awesome icons. To include the necessary fonts and styles, I am using a CDN in the main SCSS file as shown below: @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@200;300;400; ...

When using TypeScript, the tls.TLSSocket() function may trigger an error mentioning the absence of a "socket" parameter

Currently, I am in the process of building a basic IRC bot and using raw sockets to connect to the IRC server. Initially written in plain Javascript, I am now transitioning it to TypeScript. However, I have encountered an unusual issue when attempting to c ...