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

Can the Disqus API be leveraged to retrieve comments from a particular website address?

It is my preference to accomplish this task solely with client-side JavaScript scripting, if feasible. ...

The absence of a function implementation right after the declaration within a TypeScript class is a common issue that needs

I received a handwritten array to populate a table for my class, however I am now fetching this array's content from a JSON during the ngOnInit phase and it is not structured in the way I require. Therefore, I am attempting to create a function that ...

Uploading files in javascript and PHP

I am currently utilizing an audio recorder provided by this source , However, instead of storing the file locally, I am interested in uploading it back to the server. My attempt involved adjusting the Recorder.setupDownload function within the recording. ...

Validation of Single Fields in Angular Reactive Forms

When I validate a reactive form in Angular, I expect the error message to show up beneath the invalid field whenever incorrect data is entered. <form (ngSubmit)=sendQuery() [formGroup]="form"> <div *ngFor='let key of modelKeys&ap ...

Design a CreateJS/EaselJS website, comprised of multiple web pages, that is not focused on gaming

I have developed an existing HTML5 Canvas webpage composed of multiple pages, buttons, and hotspots using pure canvas javascript code. The reason I refer to 'buttons' and 'hotspots' in quotes is because I created them from scratch in j ...

What is the best way to update the style following the mapping of an array with JavaScript?

I want to update the color of the element "tr.amount" to green if it is greater than 0. Although I attempted to implement this feature using the code below, I encountered an error: Uncaught TypeError: Cannot set properties of undefined (setting 'colo ...

Creating a hierarchical JSON structure to populate a Handlebars template (HTML) for an iterative component, allowing for the display of three levels of interconnected

Currently, I am working on developing a mega menu component that involves three levels of content. Level 1 (L1): This level is displayed horizontally in a traditional navbar. When hovered over, it expands to reveal the mega menu. Level 2 (L2): These item ...

Transform a list separated by commas into an unordered list

Seeking a PHP, Jquery, or JavaScript method to convert comma-separated data into an unordered list. For clarification, I have uploaded a CSV file to WordPress where one section of content is separated by commas and I am looking to display it as a list. A ...

Using an element with the href property in conjunction with react-router: a comprehensive guide

My goal is to implement the navigation.push(url) functionality upon clicking an anchor tag element in order to prevent the app from refreshing when navigating to a new page, thus allowing me to maintain the application state. The decision to use this on a ...

Jquery Not Responding to HasChanged Function

I am a beginner and looking for some guidance. I am attempting to develop a single page app using Jquery and AJAX, but unfortunately nothing seems to be working; no errors or any other indication. There are three hyperlinks with hrefs: #/main, #/second, # ...

Vue.js does not support animation for the Lodash shuffle function

I'm having trouble getting the lodash's shuffle method to animate properly in Vue.js. I followed the code from the documentation, but for some reason, the shuffle occurs instantly instead of smoothly. When I tested the animation with actual item ...

Switch between dropdowns with jQuery

Issue at Hand: In the scenario illustrated below, there is a side navigation bar containing options that reveal a toggled section upon clicking. Specifically, if you select the third item labeled "Dolar" from the menu, a dropdown with three additional cho ...

Obtain latitude and longitude coordinates for the corners of a React Leaflet map

Currently, I am working with react-leaflet and facing a particular challenge: In my map application, I need to display pointers (latitude, longitude) from the database. However, retrieving all these pointers in one call could potentially cause issues due ...

Incorporate a binary document into a JSPdf file

I am currently utilizing JsPDF to export HTML content into a downloadable PDF. Explore the following example which involves taking some HTML content and generating a downloaded PDF file using JsPdf import React from "react"; import { render } fro ...

The issue I'm facing with the change handler for the semantic-ui-react checkbox in a React+Typescript project

Hey there! I'm currently facing an issue with two semantic-ui-react checkboxes. Whenever I try to attach change handlers to them, I end up getting a value of 'undefined' when I console log it. My goal is to retrieve the values of both check ...

What sets Koa apart when it comes to understanding the distinctions among await next(), return await next(), return next(), and next() in middleware?

The provided information explains the function of using 'await next()' in middleware to pause the middleware and initiate the next middleware downstream until all middlewares have completed execution. Once this happens, the process will start in ...

Executing Javascript within an iframe

Is there a way to include a script in an iframe? I came up with the following solution: doc = $frame[0].contentDocument || $frame[0].contentWindow.document; $body = $("body", doc); $head = $("head", doc); $js = $("<script type='text/javascript&a ...

How to use JQuery to automatically scroll to the bottom of a

I've encountered an issue with my chat conversation update function. It runs every 2 seconds, but whenever I scroll up to read older messages, the page automatically scrolls down again when it updates. This is preventing me from reading old messages p ...

The Kendo-datepicker always excludes the number zero in the day section

When I try to enter the date: 5/01/2017 The first zero in the days section is always missing when using kendo-date-picker, resulting in the following date: 5/12/17 In my HTML code: <kendo-datepicker [min]="min" [max] ...

Validating Angular UI without requiring an input field (validating an expression)

Currently, I am utilizing ui-validate utilities available at https://github.com/angular-ui/ui-validate The issue I am facing involves validating an expression on a form without an input field. To illustrate, consider the following object: $scope.item = ...