Reactive angular form validation issues upon initial click

I am currently working on a date picker component that needs validation for the month, day, and year input fields. My goal is to have the day and year input fields disabled until the month's value is valid, and the year input field disabled until the day is valid. I have a click event on my form connected to a "validate" method. This method checks if the input value is greater than 0 or less/equal to 12 (a valid month value). Strangely, when I first click on the input field to increase the value to 1, the validate function does not run. However, it works perfectly on the second click.

datepicker.component.ts

import { Component, OnInit } from "@angular/core";
import { FormGroup, FormControl, Validators } from "@angular/forms";

@Component({
  selector: "app-datepicker",
  templateUrl: "./datepicker.component.html",
  styleUrls: ["./datepicker.component.css"]
})
export class DatepickerComponent implements OnInit {
  myform: FormGroup;
  dayDisabled: boolean = true;
  yearDisabled: boolean = true;

  ngOnInit() {
    this.myform = new FormGroup({
      month: new FormControl('', [Validators.required]),
      day: new FormControl({ value: '', disabled: true }, [
        Validators.required
      ]),
      year: new FormControl(
        { value: '', disabled: true },
        Validators.required
      )
    });
  }

  get month() {
    return this.myform.get("month");
  }

  get day() {
    return this.myform.get("day");
  }

  get year() {
    return this.myform.get("year");
  }

  validate() {
    if (this.month.value >= 13 || this.month.value === 0 || this.month.value === null) {
      this.myform.controls.day.disable();
    } else {
      this.myform.controls.day.enable();
    }
  }
}

datepicker.component.html

<form [formGroup]="myform" (keyup)="validate()" (click)="validate()">
  <fieldset>
    <legend>
      <span *ngIf="month.dirty && day.disabled">
        Please enter a valid month
      </span>
    </legend>
    <div>
      <div>
        <label>
          Month
        </label>
        <input
        type="number" 
        min="1" 
        max="12"
        id="month"
        formControlName="month"
        name="month">
      </div>
      <div>
        <label>
          Day
        </label>
        <input 
        type="number" 
        min="1" 
        max="31" 
        id="day"
        formControlName="day"
        name="day">
      </div>
      <div>
        <label>
          Year
        </label>
        <input 
        type="number" 
        min="1900" 
        max="2019" 
        id="year"
        formControlName="year"
        name="year">
      </div>
    </div>
  </fieldset>
</form>

Answer №1

I was able to resolve the issue by including the "input" event handler

<form [formGroup]="myform" (input)="validate()" (keyup)="validate()" (click)="validate()">
</form>

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 an issue with Angular 18 and SignalR while compiling the application: [ERROR] Unable to resolve "url", "https", "http", "util" from eventsource

Looking to implement real-time technology in an Angular 18 application? SignalR is the chosen technology, but encountering issues during the package setup and build process. The error might be linked to the build process, potentially due to Angular moving ...

TypeScript encounters difficulty in locating the namespace within a Node.js dependency

I am faced with a situation where I have two node.js packages that each contain type declaration files. In package a, there is a namespace declared that I want to reference in package b. Package A index.d.ts declare namespace foo { export interface A ...

Enhance your production mode with @ngrx/store-devtools

Currently, I have integrated @ngrx/store-devtools instrumentation with the Chrome Extension. Is it advisable to turn off this feature for production mode? ...

The Node.js express seems to be unable to fetch the css and js files

Sharing my main.ts file in which I am facing issues with linking my css and js files. view image import express from 'express'; import {Request,Response} from 'express'; import expressSession from 'express-session'; import pat ...

How to properly cast interfaces when using Angular 4's HttpClient to fetch items

Here is the layout of my interface interface IPlacesResult { summary: { queryTime: number; // ... }; results: { id: string; // ... address: { streetNumber: number; // ... }; }[]; } To populate this interface, I ...

How can I inform Typescript that an interface will exclusively consist of defined members?

My interface looks like this interface Person { name?:string; age? :number; gender?:string } I need to reuse the same interface type, but with a modification indicating that all members will never be undefined. The updated version would look like this: ...

Customizing the appearance of a form control in response to its value in Angular's Reactive

I have a unique query regarding formatting text related to formControl in an application where the formControls are created using FormBuilder and arrays of formControls. This inquiry involves retrieving the current value of a formControl and altering the ...

What are the steps for creating grid column layouts?

How can I dynamically generate columns based on the number of items in an array? For example, if there are 5 entries in the array, the layout should be as follows: <div class="row"> <div class="col-lg-6"> 1 of 2 ...

Encountered an issue when making an Angular2 HTTP POST request - SyntaxError: JSON input unexpectedly ended

Encountering an issue while trying to post data from Angular2 to a NodeJS backend. Although the POST request is successful and the server logs the correct data, an error is displayed in the browser: An error occurred: SyntaxError: JSON.parse: unexpected ...

Changing background color during drag and drop in Angular 2: A step-by-step guide

A drag and drop container has been created using Angular 2 typescript. The goal is to alter the background color of the drag & drop container while dragging a file into it. Typescript: @HostListener('dragover', ['$event']) public onDr ...

The error message "Type 'string' cannot be assigned to type 'Condition<UserObj>' while attempting to create a mongoose query by ID" is indicating a type mismatch issue

One of the API routes in Next has been causing some issues. Here is the code: import {NextApiRequest, NextApiResponse} from "next"; import dbConnect from "../../utils/dbConnect"; import {UserModel} from "../../models/user"; e ...

Can you explain the significance of the '#' symbol within the input tag?

I was reading an article about Angular 2 and came across a code snippet that uses <input type='text' #hobby>. This "#" symbol is being used to extract the value typed into the textbox without using ngModal. I am confused about what exactly ...

React-scripts is not recognizing tests that have the .tsx file extension

Currently in the process of converting my project to TypeScript, everything is almost working perfectly. The code builds without issues and renders correctly. The only hiccup I'm facing is with my tests. I've observed that when I change a test f ...

Prevent click events on disabled tabs in PrimeNG tabMenu

I am encountering an issue with PrimeNG's p-tabMenu when it comes to disabled menu items. For example, suppose I have a tabMenu with 4 sub tabs labeled AAA, BBB, CCC, and DDD. This is how the menuItems are set up in the TypeScript component: //.... ...

As a quirk of TypeScript, it does not allow for returning a Tuple directly and instead interprets it as an Array

I need assistance with adding type-safe return to a general function created by a previous developer. Here is the current syntax: export function to(promise:Promise<any>) { return promise .then(data => [null, data]) .catch(err => [ ...

Using TypeScript's Array Union Type in defining function parameters

My scenario involves a union type of an Array with specific lengths: [ number ] | [ number, number ] | [ number, number, number, number ] The requirements are for an array with either one element, two elements, or four elements. I am attempting to create ...

Issue: Query is not re-executing after navigatingDescription: The query is

On my screen, I have implemented a query as follows: export const AllFriends: React.FunctionComponent = () => { const navigation = useNavigation(); const { data, error } = useGetMyProfileQuery({ onCompleted: () => { console.log('h ...

Angular 2 and TypeScript: Mastering Checkbox Data Binding

Below is the HTML view in which user roles are checked. I want to bind a table of modified user roles using the actualizeRoles() method. How can I achieve this? <md-accordion class="example-headers-align"> <md-expansion-panel hideToggle=" ...

Using Froala events in Angular 2: A guide

Currently, I am incorporating Froala into my Angular 2 project. I have managed to upload an image successfully but am encountering issues triggering the image.uploaded event. The Froala document provides an example of how the event should be implemented: ...

Typescript encounters transpilation issues when the spread operator is omitted for undefined values {...undefined}

I am currently working on a TypeScript project where I have encountered a peculiar issue. Within some of my TypeScript files, I am including a plain JavaScript/Node file named config.js. The content of config.js is as follows: 'use strict'; modu ...