Guide to highlighting manually selected months in the monthpicker by utilizing the DoCheck function in Angular

I'm facing an issue and I could really use some assistance. The problem seems quite straightforward, but I've hit a roadblock. I have even created a stackblitz to showcase the problem, but let me explain it first. So, I've developed my own time range selector with a specific permitted range from 02-01-2019 to 09-01-2020, following the format mm-dd-yyyy. The UI for this selector is set up correctly and works flawlessly when selecting months by clicking on them. However, manual date entry is where I am encountering difficulties and require help.

In terms of validation, I am relying on moment for the following checks:

  1. Only years 2016 and 2019 are considered valid.
  2. The startRange should not come after endRange.
  3. Date format must adhere to mm-dd-yyyy.

Note: Both startRange and endRange are bound to [(ngModel)] for their respective input fields.

monthpicker.component.html

<div class="wrapper" [class.warning-border]="isApplied">
   <input type="text" [(ngModel)]="startRange" class="start-range custom-input-field">
   ....
   <input type="text" [(ngModel)]="endRange" class="end-range custom-input-field">
   ....
</div>

Highlighted below are key methods in monthpicker.component.ts:

  1. onClick(indexClicked) - Used for mouse click selections of month names, functioning properly.
  2. triggerReflection() - This method should trigger validation upon keyboard entry of dates through the validate(startRange,endRange) method which checks against the specified criteria. A successful validation will lead to calling monthReflection(), updating the month picker tray accordingly.

Here's an excerpt of the code:

triggerReflection() {
    ....
      ....
        this.validate(this.startRange, this.endRange);
        if (this.isValidRange) {
            this.monthRangeReflection();
        } else {
            this.isValidRange = false;
        }
    } ....
}

Despite the above implementation, the reflection does not occur as expected. While exploring solutions, I came across using DoCheck to enable real-time validation during date entry:

ngDoCheck(): void {
    this.validate(this.startRange, this.endRange);
    console.log("ngDocheckCalled");   
}

My ultimate goal is to automatically reflect valid date ranges on the month tray without requiring any additional keystrokes. I prefer avoiding the use of (keydown)=triggerReflection() as it would necessitate pressing keys. For the concerned component monthpicker, here's the stackblitz. Your assistance in fixing this particular issue would be greatly appreciated

If you need further details or clarification, please feel free to ask. Thank you in advance for any help provided, as I have exhausted numerous attempts and now turn to Stack Overflow as my final resort.

Answer №1

To address your query, you can utilize the same approach as discussed in your previous inquiry. By subscribing to the valuesChanges observable of your input fields, you can easily invoke the this.triggerReflection function when users manually input dates. This subscription setup should be implemented within the AfterViewInit lifecycle hook:

export class MonthpickerComponent implements OnInit, DoCheck, AfterViewInit {
    @Output() outputToParent = new EventEmitter<string>();
    @Output('timeselectorValidation') timeselectorValidation: EventEmitter<any> = new EventEmitter();

    @ViewChildren(NgModel) dateRefs: QueryList<NgModel>;

    ngAfterViewInit() {
      this.dateRefs.forEach(ref => 
        ref.valueChanges.subscribe(() =>
          this.triggerReflection()
        )
      )
    }

I have also made a minor enhancement by including a console.log statement in the triggerReflection method. Feel free to explore the modified version of your code on Stackblitz via this link: https://stackblitz.com/edit/angular-dcugua.

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

Encountering a 404 error while trying to delete using jQuery

I have been attempting to execute a 'DELETE' call on an API, but so far I have had no success. Despite being able to access the URI and view the JSON data, my DELETE request does not work. Interestingly, other web services are able to perform thi ...

Challenges with dynamically adding rows using jQuery

I am trying to create a dynamic form that allows users to select a project and then populates tasks based on the selected project from a database query. The user can then enter hours for each task, which are updated based on the project id and task id comb ...

Preventing Content Changes When Ajax Request Fails: Tips for Error Checking

I was struggling to find the right words for my question -- My issue involves a basic ajax request triggered by a checkbox that sends data to a database. I want to prevent the checkbox from changing if the ajax request fails. Currently, when the request ...

What is the best way to link optional and undefined paths in AngularJS routing?

When it comes to AngularJS routing, I have a question. How can we combine the use of a star (*) to match paths with slashes and a question mark (?) to match optional paths? Specifically, I am looking to match both /admin/tasks and /admin/tasks/arbitrary/pa ...

What is preventing my accordion from closing completely?

I'm currently working on creating FAQ questions in an accordion format. However, I've encountered an issue where adding padding around the answer section prevents the accordion from closing completely. Removing the padding solves the problem, but ...

Achieving consistent scroll position when utilizing the history.js library to navigate back with the click of a button

I need help implementing a feature that allows users to return to the same position on a webpage when clicking the back button. A common example is on ecommerce sites where if you scroll down, click on a product, then go back, you should be taken back to t ...

Error: It seems like Material UI has updated their export structure and now `makeStyles` is no longer available in the

The export of makeStyles from @mui/material/styles has been deprecated. Despite importing from @mui/styles throughout my project, this error continues to appear. I have already tried removing the node_modules folder and reinstalled, but the issue persis ...

Material UI TreeView: Organize and present node data with multiple columns in a tree structure

const treeItems = [ { id: 1, name: 'English', country: 'US', children: [ { id: 4, name: 'Spring', country: 'Uk', ...

Guide on attaching an onclick event to a button created with a string in Next.js?

<div onClick={(event) => this.addToCart(event)}> <ReactMarkdownWithHtml children={this.props.customButton} allowDangerousHtml /> </div> In my current situation, I am facing an issue with the code above. The button is being rendered ...

Executing a JavaScript function when an element is clicked using inline

Is it possible to write the code below in a single line? <a href="#" onClick="function(){ //do something; return false;};return false;"></a> As an alternative to: <a href="#" onClick="doSomething(); return false;"></a> functio ...

What is the best way to position an image alongside text using Vue and Buefy?

I'm looking to add an image next to my text in Vue using Buefy. Take a look at the code I have so far, can someone offer some guidance? <template> <section class="hero is-link is-fullheight-with-navbar"> <div cla ...

The package-lock file may vary depending on the npm version being used

I am experimenting with a new typescript react app that was created using CRA. I am running @6.4.1 on one PC and an older version on another. Interestingly, the newer version installs dependencies with an older version instead of the expected new one. ...

Tips for retrieving a variable from an XML file with saxonjs and nodejs

I came across an xml file with the following structure: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE agent SYSTEM "http://www.someUrl.com"> <myData> <service> <description>Description</description> < ...

Having trouble with test coverage in Mocha using Blanket?

I have a Node application that I want to test and generate a coverage report for. I followed the steps outlined in the Getting Started Guide, but unfortunately, it doesn't seem to be working correctly. In my source code file named src/two.js: var tw ...

Apply a CSS class when the tab key is pressed by the user

Currently in my Angular 14 project, I am working on a feature where I need to apply "display: block" to an element once the user reaches it using the tab key. However, I am struggling with removing the "display: block" when the user tabs out of the element ...

The animation feature on the slideshow is dysfunctional

For this Vue component, I attempted to create a slideshow. The process is as follows: 1) Creating an array of all image sources to be included (array: pictures) 2) Initializing a variable(Count) to 0, starting from the beginning. 3) Adding v-bind:src=" ...

Discover the geolocation data for post code 0821 exclusively in Australia using Google Maps Geocoding

I'm having trouble geocoding the Australian postcode 0821. It doesn't seem to reliably identify this postcode as being located within the Northern Territory, unlike 0820 and 0822 which work fine. Here's an example of what I'm doing: ...

Unlocking the Sound: Using a Custom Button to Activate Audio on HTML Video in React

While working on a project, I encountered a small issue: I have a video tag in my code: <video muted autoPlay loop src={video}> I simply want to add a single custom button/control to toggle between muting and unmuting the video. I'm thinking of ...

Selecting Countries and States in Angular 2

Within my form, I have incorporated two dropdowns using <select> tags for country and state selection. The idea is that when a user picks a country, the state dropdown should automatically populate with the corresponding options. This functionality i ...

Error TS2307 - Module 'lodash' not found during build process

Latest Update I must apologize for the confusion in my previous explanation of the issue. The errors I encountered were not during the compilation of the Angular application via Gulp, but rather in the Visual Studio 'Errors List'. Fortunately, I ...