Disabling specific time slots in the mat select functionality

I have a scenario where I need to display time slots at 30-minute intervals using Mat Select.

export const TIME=["12:00 AM","12:30 AM","01:00 AM","01:30 AM","02:00 AM","02:30 AM","03:00 AM","03:30 AM","04:00 AM","04:30 AM","05:00 AM","05:30 AM","06:00 AM","06:30 AM","07:00 AM","07:30 AM","08:00 AM","08:30 AM","09:00 AM","09:30 AM","10:00 AM","10:30 AM","11:00 AM","11:30 AM","12:00 PM","12:30 PM","01:00 PM","01:30 PM","02:00 PM","02:30 PM","03:00 PM","03:30 PM","04:00 PM","04:30 PM","05:00 PM","05:30 PM","06:00 PM","06:30 PM","07:00 PM","07:30 PM","08:00 PM","08:30 PM","09:00 PM","09:30 PM","10:00 PM","10:30 PM","11:00 PM","11:30 PM"];

My goal now is to disable all past time slots starting from the current time + 2 hours.

This is the code snippet I am working with:

      <mat-select class="form-control" formControlName="pickupTime" placeholder="Select Time">
        <mat-option *ngFor="let time of times" [value]="time">
          {{time}}
        </mat-option>
      </mat-select>



    isDisableTime(selectedTime: string): boolean {
        if (moment(this.oneWayFormGroup.get('pickupDate').value).isSame(Date.now(), 'day')) {
            let isTimeOver = false;
            let currentHour = new Date().getHours() + 2;
            let currentMin = new Date().getMinutes();
            let currentAmPm = currentHour >= 12 ? 'PM' : 'AM';
            currentHour = currentHour % 12;
            let selectedHour = +selectedTime.substr(0, 2) % 12;
            let selectedMin = +selectedTime.substr(3, 2);
            let selectedAM_PM = selectedTime.substr(6, 2);
            if (currentAmPm === selectedAM_PM) {
                if (selectedHour < currentHour) {
                    isTimeOver = true;
                } else if (selectedHour === currentHour) {
                    if (selectedMin < currentMin) {
                        isTimeOver = true;
                    }
                }
            } else {
                isTimeOver = currentAmPm > selectedAM_PM;
            }
            return isTimeOver;
        } else {
            return false
        }
    }

The problem arises when the current time reaches 11 PM as all the preceding AM time slots get disabled.

You can refer to the StackBlitz link provided below for further clarification:

https://stackblitz.com/edit/angular-uekaan

Answer №1

Check if Time is Disabled:

isTimeDisabled(selectedTime: string): boolean {
    let disable = false;
    let currentHour = new Date().getHours();
    let currentMin = new Date().getMinutes();
    let currentAmPm = currentHour >= 12 ? 'PM' : 'AM';
    currentHour = currentHour % 12;
    let selectedHour = +selectedTime.substr(0, 2) % 12;
    let selectedMin = +selectedTime.substr(3, 2);
    let selectedAM_PM = selectedTime.substr(6, 2);

    if (currentAmPm === selectedAM_PM) {
      if (selectedHour < currentHour || (selectedHour === currentHour && selectedMin < currentMin)) {
        disable = true;
      }
    } else {
      disable = currentAmPm > selectedAM_PM;
    }

    return disable;
}

HTML Code for Mat-Select Dropdown:

<mat-select class="form-control" formControlName="pickupTime" placeholder="Select Time">
        <mat-option *ngFor="let time of times" [value]="time" [disabled]="isTimeDisabled(time)">
          {{time}}
        </mat-option>
      </mat-select>

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

What steps can I take to persistently subscribe to SignalR from an Angular service even in the event of connection failures?

Is there a way to safely attempt to connect to SignalR with intervals between attempts until the connection is established? Also, does anyone have advice on how to handle the different stages of connectivity to the web sockets effectively? We are utilizin ...

How to add an item to an array in JavaScript without specifying a key

Is there a way to push an object into a JavaScript array without adding extra keys like 0, 1, 2, etc.? Currently, when I push my object into the array, it automatically adds these numeric keys. Below is the code snippet that I have tried: let newArr = []; ...

Send multiple values as arguments to a jQuery function

Beginner question ahead: I'm using the jquery function loadNewPicture() to upload pictures and the progress() function to track the percentage of the upload. Everything is functioning correctly. My query relates to the variables that can be passed t ...

Issue with React container not connecting properly

I am currently facing an issue with a search bar where the input value is not displaying properly. Even when I check the value in the console, it only shows one character at a time. https://i.stack.imgur.com/Qm0Lt.png My assumption is that there might be ...

Tips for splitting JSON objects into individual arrays in React

I'm currently tackling a project that requires me to extract 2 JSON objects into separate arrays for use within the application. I want this process to be dynamic, as there may be varying numbers of objects inside the JSON array in the future - potent ...

Exploring Reactive Programming with RxJS and organizing data into individual streams

As I delve deeper into working reactively with Angular 15 and RxJS observables for a UI component, my focus lies on subscribing to data solely within the component template (html). The data is fetched from an external system through a service. However, a c ...

the angular variable scope has not been defined

Currently, I am developing an angular controller that is configured to utilize the "controller as" syntax: angular.module('app', []).controller('ctrl1', ctrl1); ctrl1.$inject = ['$http', '$compile']; function ctrl ...

Access to Angular CORS request has been blocked

I'm currently working on establishing a connection between my Angular application and a basic REST server using express. The server responds to requests with JSON data exclusively. To enable CORS support, I've integrated the cors module from npm ...

Is there a way to send all the results of a Flask database query to a template in a way that jQuery can also access

I am currently exploring how to retrieve all data passed to a template from a jQuery function by accessing Flask's DB query. I have a database table with customer names and phone numbers, which I pass to the template using Flask's view method "db ...

Stop the recurrence of multiple clicks by incorporating a Bootstrap modal popup confirmation

$('button[name="remove_levels"]').on('click', function (e) { var $form = $(this).closest('form'); e.preventDefault(); $('#confirm').modal({ backdrop: 'static', ...

Encourage (or kindly request) the user to refresh the browser

I manage a website that heavily relies on javascript and ajax functionality. I have found ways to make users refresh their browsers upon initial loading, but what about after they have already been using the site? I am looking to improve the speed of the ...

In the past, my code would run smoothly without any issues, but now I am encountering a runtime error even though the code comp

Recently, I started learning TypeScript and encountered an issue while working with Classes. My code was functioning properly before but now it's displaying a runtime error. ...

Provide a TypeScript interface that dynamically adjusts according to the inputs of the function

Here is a TypeScript interface that I am working with: interface MyInterface { property1?: string; property2?: string; }; type InterfaceKey = keyof MyInterface; The following code snippet demonstrates how an object is created based on the MyInter ...

IE does not support hover effects

Having trouble with a hover effect that works in Chrome but not in MSIE. Are there any alternatives or fixes to make it work in MSIE? The hover/rollover effects I've tried all seem to have this issue in IE. normalize.css demo.css set2.css font- ...

What is the best way to make a selected link stand out with a highlight?

I'm having an issue with the code below that is supposed to keep the selected link highlighted, but it only flashes the green color on click. Can someone help me figure out what's going wrong here? #sidebarContent a:active{ background-colo ...

Unable to load the Angular material v15 prebuild legacy theme for import

After updating Angular and Material to version 15, I encountered an issue when trying to import legacy prebuilt theme for using legacy components. Unfortunately, importing the material prebuilt-themes that are not legacy ones allows the compiler to build ...

Managing code requiring document.title in Next.js with Static Site Generation (SSG)

Currently, I have 2 dynamic SSG pages located under /blog/[slug]. Within these pages, I am rendering a component using next/link. When I click on these links to navigate to another slug, I encounter an issue. The problem arises when I want to execute some ...

Let's leverage the power of Node.js and Express with the Jade templating

My goal is to iterate over an array within a jade layout file named lessons.jade: each lesson in myLessons ul.nav.pull-center: li.dropdown.nav.text-center .btn.btn-default.dropdown-toggle.btn-lg.btn-block(data-toggle="dropdown ...

Protractor Encounters Error When Assigning Variable

var itemStatus = element(by.model('item.statusId')).getText(); This issue is causing Protractor to raise an error: Uncaught exception: Error while waiting for Protractor to sync with the page: "Angular could not be found on the window" Pro ...

A step-by-step guide on transferring Data URI from canvas to Google Sheet using the fetch method

I am trying to send an image as base64 code to a Google sheet using fetch. However, I am encountering an error that says "data_sent is not defined" when I run my code. I need help identifying the problem and finding a solution to fix it. For reference, & ...