Difficulty with validating form groups in PrimeNG calendar

I am currently implementing validation for my form. The discount field must not be empty and its value should range from 0 to 100, while the time_from and time_to fields cannot be left empty. However, I am facing an issue with firing the validation process specifically on the time_from and time_to fields. I am using the PrimeNG Calendar component and discovered that the p-calendar validation works well with ngModule, but I have been unable to find a solution for form groups.

Component (simplified)

ngOnInit() {
    this.buildForm();
  }

  buildForm(): void {
    this.discountFG = this.fb.group({
      discount: new FormControl('', [Validators.required, CustomValidators.range([0, 100])]),
      time_from: new FormControl('', Validators.required),
      time_to: new FormControl('', Validators.required)
    });

    this.discountFG.valueChanges
      .subscribe(data => this.onValueChanged(data));
  }

  onValueChanged(data?: any) {
    if (!this.discountFG) { return; }
    const form = this.discountFG;

    for (const field in this.formErrors) {
      // clear previous error message (if any)
      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

Template (simplified)

          <p-calendar formControlname="time_from" [locale]="pl" dateFormat="yy-mm-dd" [monthNavigator]="true" [yearNavigator]="true"
            yearRange="2010:2030" (blur)="setTimeFrom($event)" readonlyInput="true" required></p-calendar>

          <p-calendar formControlname="time_to" [locale]="pl" dateFormat="yy-mm-dd" [monthNavigator]="true" [yearNavigator]="true"
            yearRange="2010:2030" [minDate]="minDate" readonlyInput="true" required></p-calendar>

Current behavior

The validators do not recognize when a date is selected, leading to no event being triggered to capture the value change. As a result, the onValueChanged function incorrectly assumes that time_from and time_to have not been interacted with.

How can I resolve this issue ?

Answer №1

After conducting an extensive debugging session, I discovered that the form was not validating due to a syntax error :( It seems that you mistakenly spelled formControlName with a lowercase n. This small typo prevented the form controls from receiving the necessary values.

I rectified this issue in Plunk and upon testing it again, everything functioned as expected.

Here is the corrected html:

<form (ngSubmit)="onSubmit()" [formGroup]="discountFG" class="box-model form-support-margin">
  <p-calendar formControlName="time_from" dateFormat="yy-mm-dd" [monthNavigator]="true" [yearNavigator]="true"
            yearRange="2010:2030" (blur)="setTimeFrom($event)" readonlyInput="true">

  </p-calendar>

          <p-calendar formControlName="time_to" dateFormat="yy-mm-dd" [monthNavigator]="true" [yearNavigator]="true"
            yearRange="2010:2030" [minDate]="minDate" readonlyInput="true"></p-calendar>
  <p></p>
  <button md-raised-button color="primary" type="submit" [disabled]="!discountFG.valid">Save</button>
</form> 

Plunker Demo

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

What is the best way to avoid curly braces in an Angular template?

If I need to show the following string, including the {{ }}, in an Angular 2+ template: Hello {{name}}, how are you?" Note: The entire string will be hardcoded, not from a variable. What is the optimal method to encode the curly braces so they are not ...

Guide to Implementing Dependency Injection in Angular 2

When working with Angular Components written in TypeScript, it is possible to declare a class member (variable) as a parameter of the constructor. I am curious about the reason for doing so. To clarify, take a look at the examples below. Both achieve the ...

Implementing data binding in ngStyle with Angular

Having trouble binding data with Angular 8, I attempted the following method: <div class="speed" style="background-image: url('http://example.com/assets/images/meter.png')" [ngStyle]="{'--p':result.percentage}"></div> The ...

Steps for Properly Defining Next.js getServerSideProps as a Function Declaration

I've been working on implementing getServerSideProps (additional information available here, and detailed API documentation here), but my challenge lies in utilizing it as a function declaration instead of an expression. Despite searching for relevant ...

The element 'PROGRAM_ID' is not recognized within the 'import @metaplex-foundation/mpl-token-metadata' type

I am currently in the process of creating a token within the Solana network, but I've encountered a particular issue. I have successfully installed @metaplex-foundation/mpl-token-metadata and integrated it into my code; however, an error is persisting ...

The data that has been retrieved is not currently displayed within the Vue table

I'm currently exploring js/vue and I'm attempting to retrieve data from an API. There's a field where the value is used to fetch data from the API based on that keyword. When I check the console log, I can see that the data is being received ...

Instead of relying on a button click to trigger a script, set up the script to load automatically when inputs are detected

Recently, I created a simple calculator web-app using Angular. In my app.component.html file, I have the following code: <div style="text-align:center"> <h1>Calculator</h1> <input type="text" id="firstNumber" placeholder="Firs ...

Leverage the power of AWS SDK Amplify to securely retrieve a folder stored in an

Currently, I am utilizing amplify to retrieve a folder from S3. However, it seems that only a single file can be downloaded using this method, unlike the .NET SDK which offers the DownloadDirectoryAsync function. Does anyone know of a solution or workaroun ...

Issue with Angular9-MatDatePicker: Unable to establish a connection with 'ngModel' as it is not recognized as a valid attribute of 'input'

Despite my efforts to implement ngmodel binding with matdatepicker, I am still encountering issues, even after reviewing multiple other posts on the topic. Here is a snippet of my HTML: <mat-form-field> <mat-label>Start Date</mat-label ...

How to include an image in a file type using Angular 2 and TypeScript

Is it possible to assign an image to a file type variable in Angular 2? I attempted the following approach: private file:File; setImage(){ this.file = "../assets/image/image.jpg" } Unfortunately, this method did not succeed. ...

I rely on the angular-responsive-carousel library for my project, but unfortunately, I am unable to customize the arrow and dots

When it comes to CSS, I utilize ng deep style in Angular 10 to make changes for browser CSS. However, I am facing an issue where the problem is not being resolved by my CSS code. Here is a snippet of my code: > ::ngdeep .carousel-arrow { > b ...

Using Angular 4: Redirecting Menu to Component with Electron

I am currently working on my first project using Angular 4 and Electron to develop a desktop application. One of the challenges I'm facing is figuring out how to redirect to a specific component when a submenu item is clicked after overriding the ele ...

What is the method to access the information within the observer?

When I receive the data from the observer in the console, here is what I see: https://i.stack.imgur.com/dVzwu.png However, I am only interested in extracting this specific data from each item on the list: https://i.stack.imgur.com/g8oHL.png To extract ...

Ag-grid with Angular 2 allows users to easily edit entire columns with just a few

I need help modifying a column in my ag-grid. My ag-grid currently looks like this: grid image I want to update all values in the column Etat to be arrêté, but I'm struggling to make it work. This is the code I've been trying: private gridO ...

Executing a single insert statement in a TypeScript Express application using PostgreSQL is taking over 240 milliseconds to complete

Seeking assistance with optimizing a db insert operation test using mocha for a node.js express app that utilizes fp-ts and pg npm package. The tests run successfully, but the insert test is taking over 240 ms to complete. The database table has a maximum ...

Error message: Angular Universal running on Docker encountered an HTTP failure response from an unidentified URL

My current setup consists of the following: I have four services defined in my docker-compose.yml file: my_nginx, my_client, my_api, and my_db. Using my_nginx as a proxy pass to access my_client:8000 and my_api:8001, both running on Node.js. The my_clie ...

Troubleshooting Angular 2: (keyup) event not functioning on Tour of Heroes Tutorial

I am currently working on a tutorial for the tour of heroes, and I have encountered an issue with the (keyup) event in my project. What seems to be happening is that when I input the first letter, Angular sends a request, but subsequent key presses do not ...

Error message in my Angular project: Invalid Target Error

Out of nowhere, I encountered an invalid target error while running my Angular project with the command: npm start An unhandled exception occurred: Invalid target: {"project":"agmbs","target":"build","configur ...

Implementing lazy loading in a different ng-module: Step-by-step guide

I currently have two ng-modules set up Dash Board Repeat order list I loaded the Repeat order module through lazy loading. Now I am trying to integrate the Repeat order module inside the dashboard as HTML content <app-repeatorderlist></app-re ...

Encountered difficulties in deploying functions on Firebase Cloud Functions

While developing the Firebase Cloud Functions, I organized the files based on each function. Unfortunately, numerous errors occurred during deployment. Error [debug] [2022-07-19T14:36:17.677Z] <<< [apiv2][body] GET https://us.gcr.io/v2/xxxxxx/gcf ...