Ways to deactivate certain dates in ion-datetime?

In my Ionic3/Angular app, I am utilizing ion-datetime to choose a specific date. However, I would like to disable certain dates within the ion-datetime component. Despite reviewing the documentation, I couldn't find any clues on how to accomplish this task.

Is there anyone who can provide guidance on this matter?

Answer №2

Summary - Use

[isDateEnabled]="isBlockedDate"
to calculate blocked dates by passing a date string (eg '2022-08-23')

--

In Ionic 6, the new property isEnabledDate can be used to block specific dates.

isBlockedDate = (dateString: string) => {
  const result = this.current_month_blockout_dates.some((date) => {
    let interstitial_date = `${date.years}-${('0' + (date.months)).slice(-2)}-${date.date}`;
    // Example: comparing 2022-08-21 with 2022-08-12
    return dateString == interstitial_date;
  });
  if(result === true) {
    console.log(`Blocked confirmation for date: ${dateString}`, result);
  }
  return !result;
}

If you populate the array

this.current_month_blockout_dates
with relevant dates, refer to how the code works above:

this.current_month_blockout_dates = [{years:'2022', months:'10', date:'14'}];

To use, make sure to include

[isDateEnabled]="isBlockedDate"
, like so:

<ion-datetime 
#orderDatePicker 
id="orderDatePicker"
size="fixed"
(click)="createDateListeners()"
[isDateEnabled]="isBlockedDate"
presentation="date"
max="2025"
[min]="todaysDate">
</ion-datetime>

Extra Tip
You can set up an observer to recalibrate your blocked dates when the month changes:

createDateListeners() {
  // Observe Date changes
  const self = this;
  var previous = '';
  const targetNode = document.querySelector('ion-datetime#orderDatePicker');
  const config = { attributes: true, childList: true, subtree: true };
  const callback = function(mutationsList, observer) {
      for(const mutation of mutationsList) {
          if (mutation.type === 'attributes') {
              var e = document.querySelector('ion-datetime#orderDatePicker').shadowRoot.querySelector('ion-label').textContent;
              if(e !== previous)
              {
                  previous = e;
                  console.log('[Date Listener]: e', e);
                  let date_interpret = new Date(e);
                  self.current_month = date_interpret.getMonth()+1;
                  console.log('[Date Listener]: Current month', self.current_month);
                  self.current_month_blockout_dates = self.checkMonth(self.current_month);
                  
                  return;
              }
          }
      }
  };
  const observer = new MutationObserver(callback);
  observer.observe(targetNode, config);
}

The function I use is called checkMonth, but feel free to customize it according to your needs. Best of luck.

Answer №3

This solution is effective for my needs.

index.html

<ion-datetime
 presentation="date"
 locale="es-ES"
 hourCycle="h24"
 [min]="minDate"
 [isDateEnabled]="isDateEnabled"
></ion-datetime>

index.ts

  disabledDatesArray: string[] = ['2025-02-11', '2025-02-18'];

  isDateEnabled = (dateString: string) => {
    const date = new Date(dateString);
    const formattedDate = this.formatDateUTC(date);

    return !this.disabledDatesArray.includes(formattedDate);
  };

  private formatDateUTC(date: Date): string {
    const year = date.getUTCFullYear();
    const month = (date.getUTCMonth() + 1).toString().padStart(2, '0');
    const day = date.getUTCDate().toString().padStart(2, '0');

    return `${year}-${month}-${day}`;
  }

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

Embracing the power of mixins in Vue.js

Currently in the process of learning app development with Vuejs. In my main.js file, I have the code for setting up Vue.js. Recently, I created a new directory called /mixins and added a file named api.js. My intention is to use this as a mixin so that eve ...

Switch between multiple child elements within a list using jQuery's toggle method

Review my HTML code below. I am attempting to create a function where when Level1 is clicked, it will hide all child ul and li elements of Level1. Then, when clicked again, it will show them - toggling between the two states. Similarly, if Level2 is clicke ...

Angularjs scope throws TypeError when attempting to add an array

As someone diving into the world of Angular and JavaScript, I am tackling the challenge of creating a directive that requires adding an array to the directive's scope. Here's a snippet of the code for my directive: .directive("startupSections", ...

using a unique first argument in Javascript when calling the apply method

In this particular scenario, the output varies depending on the first argument passed to apply The snippet of code looks like this: var fruitarray = []; fruitarray[0] = ['strawberry', 'orange']; fruitarray[1] = ['lime', &a ...

Using a custom module in node.js to retrieve data from a mysql database

How can I retrieve select query results? I am currently getting empty or null responses. Despite attempting callback logic and using the callback function as suggested in some articles, I have yet to have any success. All of the code for my Custom Module ...

React's setState method may not trigger a re-render

I am currently working on a personal project using React for the front-end and Node for the back-end. One part of the application involves counting the entries when a user submits an image URL, updating it on the server, and then re-rendering it on the fro ...

Jquery Issue: Safari Leaves Alert Messages Unclosed When Opening Next Alert

I am experiencing an issue in Safari Browser and need some help with the following scenarios (with Example). When I click a button to delete an account, an alert message pops up. This alert window has two actions - "OK" and "Cancel". If I click "OK", it r ...

Replicating JavaScript functions with the power of Ajax

I'm facing an issue with Bootstrap modal windows on my page. The modals are opening and closing successfully, but the content inside them is fetched through AJAX as HTML. For example, there's a button in the modal: <button id="myBtn"> and ...

Managing JSON Forms using jQuery on Google's App Engine

Having difficulty getting jQuery to function properly on GAE in python 2.7. The main issue is that jQuery is unable to retrieve the json data sent by the server. A basic comment form with no special features: <form action="/postcomment/" method="post" ...

Is it appropriate to use localStorage in the createSlice "reducers" parameter of React Redux Toolkit?

I'm working on implementing a basic favorites list feature. Currently, there is no backend functionality in place so this will be stored in the localStorage. It might potentially switch to an API call in the future. Would it be considered acceptable ...

Incorporating an event listener for 'storage' in jQuery using JavaScript

Can anyone tell me how to achieve the same functionality as javascript addEventListener in JQuery? I have been attempting to use it with .bind(), but it seems not to recognize the "storage" keyword. When I tried using 'e' within this context, it ...

Mastering the art of MUI V4: Implementing conditional row coloring

I've encountered an issue with my basic Material UI v4 datagrid. I'm attempting to change the color of any row that has an age of 16 to grey using color: 'grey'. However, I'm finding it challenging to implement this. The documentat ...

Why is my React-Redux API Get request action not running?

Hello there! I am currently working on integrating React-Redux with my Flask API to display JSON data on my website. Although the API is functioning properly, I seem to be facing an issue where the action called does not execute. As a beginner in Redux, I ...

Reversed key-value pairs mistakenly included in JSON string and passed to Django view using POST method

This is my initial dive into ajax, where I have created a submit handler that extracts form data and sends it to the server via POST in JSON format. Below is a basic overview of my JavaScript code: formData = JSON.stringify({'testA':{'testa ...

Attempting to navigate through nested data within existing mapped data

The data set 1 consists of an array that contains another array called data set 2. Currently, data set 1 is being mapped to display a single-column table with data1.name inside it. The data1.name serves as a clickable button that reveals the related data i ...

What is the jQuery equivalent for converting this JavaScript code?

Here's a code snippet that I am struggling with: data=>{document.querySelector( "#os11.html-widget.gauge svg text[font-size='10px'] tspan" ).innerHTML = data.text I attempted the following solution: $("#os11.html ...

Various relationships in Sails.js

Exploring associations in Sails.js beta (version 0.10.0-rc4) has been quite intriguing for me. My current challenge involves linking multiple databases to produce a unified result (utilizing sails-mysql). The association scheme I'm working with invo ...

What is the best way to replace input fields with processed values?

I'm struggling to restrict the characters permitted in a number input field. Currently, I am unable to figure out how to remove invalid characters from the inputfield. Below is the code snippet that I am experimenting with: <template> <di ...

This error message in AngularJS indicates that the argument 'fn' is not being recognized as a function

I am currently working with angularjs and typescript and I am attempting to create a directive in the following manner: Below is my controller : export const test1 = { template: require('./app.html'), controller($scope, $http) { ...

How can I update my EJS template in ExpressJS after retrieving JSON data using NodeJS?

Utilizing NodeJS, I am making API calls and passing the data to my EJS template through ExpressJS with the following code snippet: app.get('/', function (req, res) { res.render('routes/index', { plLoopTimes: plLoopTimes, pl54Ti ...