How come the Angular8 form status registers as VALID even if the input fields are empty?

The following is the structure of the component:

  export class SchedulerComponent implements OnInit {

  schedulerForm : FormGroup;
  constructor(private fb: FormBuilder,
              private schedulerReportService: SchedulerReportService) { 

    this.prefReport = "dayReport";
    this.schedulerForm = this.fb.group({
      schedulerCategory:['dayReport'],
      dayReport: this.fb.group({
        d_date: ['',Validators.required],
        d_runTime: ['',Validators.required],
        d_timeZone: ['',Validators.required],
      }),
      rangeReport: this.fb.group({
        r_runTime: [''],
        r_startDate: [''],
        r_endDate: [''],
        r_timeZone: ['']
      }),
    });
    this.onValueChanges()

  }
  @Output() change: EventEmitter<MatRadioChange>; 
  @Output() scheduleEvent = new EventEmitter<ScheduleService>();

  showScheduler = false
  prefReport : string

  dayReport = true;
  rangeReport = false;

  ngOnInit() {

    this.setScheduleFormValidators();
  }

  onValueChanges(): void {

    this.schedulerForm.valueChanges.subscribe(val=>{

     console.log(this.schedulerForm.status)
     if(this.schedulerForm.status === 'VALID'){

      let scheduleServiceModel = new ScheduleService(val)
      this.scheduleEvent.emit(scheduleServiceModel)
      } 
    })
  }


  toggled(){
    this.showScheduler = !this.showScheduler;

  }

  radioSelect(event : MatRadioChange){

    let radioSelect=event.value;
    this.schedulerForm.reset();
    if (radioSelect == 'dayReport'){
      this.dayReport = true;
      this.rangeReport = false;
      this.schedulerForm.get('schedulerCategory').setValue('dayReport');
    }else if(radioSelect == 'rangeReport'){
      this.dayReport = false;
      this.rangeReport = true;
      this.schedulerForm.get('schedulerCategory').setValue('rangeReport');

    }
  };

  setScheduleFormValidators() : void {
    const drunTime = this.schedulerForm.get(['dayReport','d_runTime']);
    const ddate = this.schedulerForm.get(['dayReport','d_date']);
    const dtimeZone = this.schedulerForm.get(['dayReport','d_timeZone']);

    const rrunTime = this.schedulerForm.get(['rangeReport','r_runTime']);
    const rtimeZone = this.schedulerForm.get(['rangeReport','r_timeZone']);
    const rstartDate = this.schedulerForm.get(['rangeReport','r_startDate']);
    const rendDate = this.schedulerForm.get(['rangeReport','r_endDate']);

    this.schedulerForm.get('schedulerCategory').valueChanges
    .subscribe(schedulerCategory => {
      if (schedulerCategory === 'dayReport') {
        drunTime.setValidators([Validators.required]);
        ddate.setValidators([Validators.required]);
        dtimeZone.setValidators([Validators.required]);
        rrunTime.setValidators(null);
        rtimeZone.setValidators(null);
        rstartDate.setValidators(null);
        rendDate.setValidators(null);
      }
      else if (schedulerCategory === 'rangeReport') {
        drunTime.setValidators(null);
        ddate.setValidators(null);
        dtimeZone.setValidators(null);
        rrunTime.setValidators([Validators.required]);
        rtimeZone.setValidators([Validators.required]);
        rstartDate.setValidators([Validators.required]);
        rendDate.setValidators([Validators.required]);

      }
      drunTime.updateValueAndValidity();
      ddate.updateValueAndValidity();       
      dtimeZone.updateValueAndValidity();
      rrunTime.updateValueAndValidity();
      rtimeZone.updateValueAndValidity();
      rstartDate.updateValueAndValidity();
      rendDate.updateValueAndValidity();

    });

  }

}

When the radioSelect() function is executed, a form group is displayed to the user. Upon running the application and filling out the default form, everything works as expected. However, if I switch the radioSelect(), an issue occurs in the console where the status becomes invalid until schedulerCategory is updated (even though it's just one field):

scheduler.component.ts:64 INVALID
scheduler.component.ts:64 INVALID
scheduler.component.ts:64 INVALID
scheduler.component.ts:64 INVALID
scheduler.component.ts:64 INVALID
scheduler.component.ts:64 INVALID
scheduler.component.ts:64 INVALID
scheduler.component.ts:64 VALID

While monitoring the value changes on the form, after switching without completing any fields, the form.status appears valid in the form.valueChanges subscriber. There seems to be something missing here that I can't quite identify. Any insights would be greatly appreciated!

Answer №1

In most cases, I tend to use the .valid and .dirty properties to filter the valueChanges.

myForm.valueChanges.pipe(
   filter(() => myForm.valid && myForm.dirty)
   )
.subscribe(values => ...

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

The type 'typeof globalThis' does not have an index signature, therefore the element is implicitly of type 'any'. Error code: ts(7017) in TypeScript

I'm encountering an issue with my input handleChange function. Specifically, I am receiving the following error message: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.ts(7017) when att ...

Encountering the error message "String length is invalid" during the execution of ng build for a library

While working with Angular and attempting to build a large library using the command ng build <project>, we encountered the following issue: ❌ Generating "fesm2015" Invalid string length The build for fesm2020 was successful, but the sourcem ...

Learn the steps to dynamically show a navbar component upon logging in without the need to refresh the page using Angular 12

After logging in successfully, I want to display a navbar on my landing page. Currently, the navbar only shows up if I reload the entire page after logging in. There must be a better way to achieve this without a full page reload. app.component.html <a ...

What is the correct way to define the onClick event in a React component?

I have been encountering an issue while trying to implement an onClick event in React using tsx. The flexbox and button are being correctly displayed, but I am facing a problem with the onClick event in vscode. I have tried several ideas from the stack com ...

Using jQuery for client-side validation when the user clicks a button in an ASP.NET application

My goal is to implement field validation on button click using Jquery, but I'm facing an issue where it seems like the code behind event and the jQuery event are executing simultaneously. (UPDATED) <asp:Button ID="btnsave" runat="server" ClientI ...

Encountering an error stating "Argument of type 'X' is not assignable to parameter of type 'X' in the NextApiResponse within NextJS."

Here is the code snippet I am working with: type Data = { id: string; name: string; description: string; price: number; }; const FetchMeals = async (req: NextApiRequest, res: NextApiResponse<Data>) => { const response = await fetch( ...

Tips for troubleshooting an Angular app with just a single click using WebStorm!

After conducting some research, I have checked the following resources: How to debug an application in Angular2 using angular-cli? https://manuel-rauber.com/2016/09/30/how-to-debug-angular-2-with-webstorm/ The troubleshooting method mentioned on the Je ...

What are some strategies for managing multiple versions of NPM and Node? Is there a way to install Angular for a single project without affecting other projects?

I have been tasked with working on two separate projects that rely on NPM and Node. The first project was developed using Ionic, while the new one requires Angular exclusively. Initially, only the Ionic project was set up on my laptop, so all installations ...

Issue with ESLint error in TypeScript PrimeReact async Button click handler

I am currently facing an issue with exporting data from a DataTable in PrimeReact. The onClick function for the Button does not allow async callbacks as flagged by eslint. Can someone guide me on how to properly call this function? const exportCSV = us ...

Is it possible to adjust the height of the dropdown menu in a mat-select component in Angular 7?

How can I adjust the height of a mat-select in Angular7 to display all items properly? Here is my component file: import { Component, ViewEncapsulation } from "@angular/core"; import { FormControl } from "@angular/forms"; /** @title Select with multiple ...

Running NG BUILD from Gulp can be done using either child-process.spawn or by disabling all output in child-process.exec

Have you come across a similar question like this Call "ng build" from inside a gulp task? I have found a way to successfully build Angular using Gulp in order to prevent overflowing the output buffer. Here's how I achieved it: const child ...

Make Ionic 2 Navbar exclusively utilize setRoot() instead of pop()

When navigating to a different page, the ion-navbar component automatically includes a back button that uses the pop() method to return to the previous page. Is there a way to modify this behavior so that it utilizes the setRoot() method instead of pop(), ...

Issue TS2349 occurs when attempting to use a combination of boolean and function types within union typing

In my class, there is a property called "isVisible" which can be either a boolean value or a function that returns a boolean. The code snippet below demonstrates what I am currently using. It works fine and achieves the desired result, but during compilat ...

Is it possible to manually activate a dropdown event using pure JavaScript?

I am attempting to manually trigger a dropdown event using JavaScript. Below is the function where I am trying to achieve this. I have successfully halted the initial event that occurs and now I need to initiate a dropdown event. stopNavigationTriggerDrop ...

What is the most secure method to define options and retrieve their values in a type-safe manner?

I am currently utilizing a library that offers an interface with a great deal of flexibility. type Option = number | { x?: number; y?: number; z?: number; } interface Options { a?: Option; b?: Option; c?: Option; d?: Option; } function init ...

Asynchronous handling of lifecycle hooks in TypeScript for Angular and Ionic applications

I'm intrigued by the idea of integrating TypeScript's async/await feature with lifecycle hooks. While this feature is undeniably convenient, I find myself wondering if it's considered acceptable to make lifecycle hooks asynchronous. After ...

Display the most recent information retrieved from Local Storage using Angular 7 [Resolve]

In my application, I have a component called "edit-user" where users can edit their name or surname. This data is properly loaded and refreshed in the Local Storage, and the service works fine as the new data reflects changes in the database. However, the ...

Angular - Retrieving information through an Angular service

Currently, I am attempting to retrieve some details. Below is the code that I have written to achieve this: data.service.ts import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import 'rxj ...

Contrasting between betting text and console error logging in Angular

Currently working on an Angular application and exploring the best practices for error logging. I'm pondering whether to opt for console logging or text-based logging. Text-based logging seems beneficial as it stores historical error data on the serv ...

Dropdown Pattern with React CTA Modal

While using MaterialUI's ButtonGroup for a dropdown menu, I encountered an issue trying to set up a series of CTAs that are easily interchangeable within it. The goal is to have all components reusable and the choices in the dropdown dynamic. const C ...