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

Submitting a PDF document to the server with PHP Laravel through AJAX

Struggling to send a PDF file via AJAX to my server for handling by a PHP script in a Laravel project. The file doesn't seem to be making it to the server. Despite receiving a 200 response in the network, the server is returning 'file not presen ...

Discover the power of combining app.use and app.get in Node.js for enhanced functionality

I am working on a React application that is rendered by my Node server. I would like to not only render my React app but also call my server as an API to receive some data. How can I achieve this? Below is a snippet from my Node server: .... app.use(&a ...

The port is not defined in the express when running with the command "node ."

After going through the tutorial mentioned here, everything was smooth sailing until I reached the part where I had to run the server: https://www.digitalocean.com/community/tutorials/setting-up-a-node-project-with-typescript Attempting to execute the cod ...

JQuery, Draggable delete

I created a shopping cart with drag-and-drop functionality for nodes. http://jsfiddle.net/dkonline/Tw46Y/ Currently, once an item is dropped into the bucket (slot), it cannot be removed. I'm looking to add that feature where items can be removed from ...

Leveraging the power of AngularJS to run JavaScript functions saved as strings

Is it possible to dynamically inject JavaScript code that is stored in a string into AngularJS controllers? var dynamicJS = "function DoSomething(value){var x = 1+1 return 2;}" I need to inject the above function dynamically into my AngularJS controller ...

What is the process for utilizing jQuery's advanced ticker feature to extract content from a text file?

I am currently implementing this code on my website: <script> var file = "http://newsxpressmedia.com/files/theme/test.txt"; function getData(){ $.get(file,function(txt){ var lines = txt.responseText.split("\n"); for (var i = ...

Is it possible for dynamically created components to trigger output events?

My objective: Dynamically create components (completed) Enable dynamically created components to utilize "outputs" so that parent Components can listen for changes from the children. Here is a Plnkr showcasing what I am trying to achieve: Plnker -> ...

What are the different methods for completing a form?

From what I understand, there are 2 methods for submitting a form. For instance, in asp.net, there is the Button.UseSubmitBehavior property which Specifies whether the Button control uses the client browser's submit mechanism or the ASP.NET postb ...

Is there a way to easily access the last element of an array in an Angular2 template without the need to iterate through the entire

I'm not trying to figure out how to access looping variables like i, first, last. Instead, my question is about how to retrieve and set variables as template variables. My current approach doesn't seem to be working... <div #lastElement="arr ...

Can you explain the significance of the @ symbol in TypeScript/Vue?

I've recently embarked on a new VueJS project and stumbled upon some unfamiliar syntax. I have highlighted the lines with comments below. file(example) : MyModule.vue const storeCompte = namespace("compte") // namespace is based on 'no ...

Timeout reached during Protractor testing on an Angular webpage

I have developed a basic Angular portal page. The main feature is a search bar where users can enter the name of an NBA team like "Chicago Bulls", "Indiana Pacers", etc. Upon submitting the team name, users are directed to a second page where they can view ...

Refused to run script from inline content on the lightweight server due to security policy restrictions

I have been adhering to Angular's best practices in order to create a Progressive Web App (PWA). After building the production version (ng build --prod --aot), I am running it from the dist folder on localhost using npm run dev ("dev": "lite-server"). ...

Facing unexpected behavior with rxjs merge in angular5

import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/merge'; this.data = this.itemsCollection.valueChanges() this.foo = this.afs.collection<Item>('products') .doc('G2loKLqNQJUQIsDmzSNahlopOyk ...

Troubleshooting issues with JavaScript's window.location.href functionality

Trying to change the URL using window.location.href doesn't seem to be working for a specific link. The current page URL is: http://localhost:37368/Office/Search/c2VhcmNoaWRzPTEyMiwxMjIsMTI0LDE1OCwzNzl8bG9jYXRpb25pZHM9MSwyfGZyb21pZHM9fHRvaWRzPQ== Af ...

What is the purpose of specifying the props type when providing a generic type to a React functional component?

When utilizing the @typescript-eslint/typedef rule to enforce type definitions on parameters, I encountered an issue with generically typing a React.FC: export const Address: React.FunctionComponent<Props> = (props) => ( An error was thrown st ...

What is the best way to test for errors thrown by async functions using chai or chai-as-promised?

Below is the function in question: async foo() : Promise<Object> { if(...) throw new Error } I'm wondering how I should go about testing whether the error is thrown. This is my current approach: it("checking for thrown error", asy ...

Looking for nested objects within an array in JavaScript

Currently, I am dealing with a REST API that provides data in the following format: students = [{ batch_id: 22 id: 1 image: null name: "a new batch student", attendance: [ { id: 1, student_id: 1, batch_id: 22, absent_on: "2019-09-15", ti ...

Can AngularJS Filters be used to convert a number into a string, but not the other way around?

After researching Angular JS filters, I discovered that the number filter is used to format a number as a string. However, there doesn't seem to be a built-in filter for converting a string to a number. In an attempt to solve this issue, here is so ...

Developing tests for an asynchronous function

I recently encountered a bug in my AWS Lambda code written in NodeJS 6.10 that caused me two sleepless nights. I didn't conduct integration testing, relying solely on unit tests, which led to the oversight. After inserting return workerCallback(err);, ...

What is the best way to generate a linked list from a JSON array?

I have a list of universities that I generated from a JSON file and now I want to create hyperlinks for each university in the list so that users can navigate to their respective university pages. HTML <ul data-bind="foreach: university"> <li ...