Is there a way to set the submitted variable to true when the form group is submitted, then revert it to false when the user makes changes to the form?

With just one FormGroup, I ensure that when a user submits the form with errors the 'submitted' variable is set to true, displaying the errors. However, my challenge now is how to reset this variable to false when the user makes any changes after submission. Can anyone suggest a solution for this tricky situation?

Answer №1

It seems like you are experiencing issues with error messages displaying after submission of your form. Keeping track of the form state with your current approach can be challenging, but there are some tricks you can utilize:

this.userForm.markAsPristine();
this.userForm.markAsUntouched();

Another suggestion would be to consider a different method:

Rather than showing errors only after submission, you could leverage reactive forms to display errors instantly for each field in your form. The submit button should only be enabled when the form is valid.

Note: If the error message originates from the backend, you may want to consider using a toast or snackbar notification.

Answer №2

Within the initialization of your component, make sure to subscribe to the changes in values of the user form by using the valueChanges property within the FormGroup.

This way, whenever a new value is emitted through valueChanges, you can automatically reset the submitted boolean property to false.

ngOnInit(): void {
   this.userForm.valueChanges.subscribe(() => {
      this.submitted = false;
   });
}

Answer №3

I believe this information could be beneficial to you

component.html

  <input type="text" class="form-controls inputs" id="planName" formControlName="plan_name" />
            <span class="title" *ngIf="(newPlanForms.plan_name.touched || submitted) && newPlanForms.plan_name.errors?.required">
            Plan name is required
            </span>

component.ts

submitted = false;

newPlanForm = this.fb.group({
plan_name:new FormControl("",[Validators.required]),});

onSubmit(value:any){
this.submitted = true;
....
.....}

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 difficulties retrieving information from an API using Angular

I am encountering an issue while trying to retrieve data from an API. When I use console.log() to view the data, it shows up in the console without any problem. However, when I attempt to display this data in a table, I keep receiving the error message: ER ...

Maintaining accurate type-hinting with Typescript's external modules

Before I ask my question, I want to mention that I am utilizing Intellij IDEA. In reference to this inquiry: How do you prevent naming conflicts when external typescript modules do not have a module name? Imagine I have two Rectangle classes in different ...

Having trouble with Angular 2 not properly sending POST requests?

Having some trouble with a POST request using Angular 2 HTTP? Check out the code snippet below: import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import 'rxjs/add ...

Top Tip for Preventing Angular Version Compatibility Issues

Here is an illustration that delves into my inquiry ----> Version Conflict The dilemma arises when my product has a dependency on a node package, which in turn relies on a specific version of Angular, denoted as version #y. However, my product itself ...

After logging in, the query parameters (specifically code and state) are still present

After logging into my SPA, the query parameters code and state are not removed from the URL. This causes an issue when refreshing the page because the login flow attempts to use the parameters in the URL again. For example, here is the URL after logging in ...

What is the best way to manage various Firebase Cloud Function API endpoints for different environments, such as DEV and PROD?

I am currently developing an Angular application hosted on Firebase. I am facing a question regarding the best approach to handle the same application being deployed in two different environments (DEV and PROD), each associated with a separate Firebase pr ...

Creating dynamic charts using Angular 7 with Chartjs and mapping JSON data

Struggling to map JSON Data for a Bar-Chart display. The desired final Array should be: [883, 5925, 17119, 27114, 2758]. Seems like the Array I'm trying to use for barChartData (dringlichkeitenValues[]) is empty. Apologies for my coding skills. Can so ...

Tips for accessing child elements within an Angular component

I'm struggling to get a reference of child elements within a component. I have experimented with ElementRef, TemplateRef, QueryList, ViewChild, ViewChildren, ContentChild, and ContentChildren without success. <app-modal> <section #referenc ...

Transmitting form data inputted by the user to a modal that resides in the same component, all without the need for child or parent components or

In need of a solution where users can input answers to questions and have all the entered data displayed in a popup alongside the respective question. If a user chooses not to answer a question, I do not want that question or any related information to be ...

Error encountered in Intellij for Typescript interface: SyntaxError - Unexpected identifier

I am currently testing a basic interface with the following code: interface TestInterface { id: number; text: string; } const testInterfaceImplementation: TestInterface = { id: 1, text: 'sample text' }; console.log(testInterface ...

What is causing the incompatibility of these generic props?

I am encountering compatibility errors when using two React components that have props accepting a generic parameter TVariables. These props include the fields variables of type TVariables and setVariables of type (vars: TVariables) => void. Even thoug ...

The Angular dependency provider is failing to supply the requested alternative class

I am currently in the process of writing unit tests for the doc-manager.component component. This particular component relies on the DocService, but I want to swap it with instances of MockedDocService within my tests. By leveraging alternative class prov ...

Accessing an external API through a tRPC endpoint (tRPC Promise is resolved before processing is complete)

I want to utilize OpenAI's API within my Next.js + tRPC application. It appears that my front-end is proceeding without waiting for the back-end to finish the API request, resulting in an error due to the response still being undefined. Below is my e ...

Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance w ...

Headers and data organization in Angular 2

I'm searching for a simple Angular 2 example that demonstrates how to fetch both the headers and data from a JSON API feed. While there are plenty of examples available for fetching data only, I haven't been able to find any that show how to retr ...

Splitting code efficiently using TypeScript and Webpack

Exploring the potential of webpack's code splitting feature to create separate bundles for my TypeScript app has been a priority. After scouring the web for solutions, I stumbled upon a possible lead here: https://github.com/TypeStrong/ts-loader/blob/ ...

What is the best way to categorize an array based on a specific key, while also compiling distinct property values into a list

Suppose there is an array containing objects of type User[]: type User = { id: string; name: string; role: string; }; There may be several users in this array with the same id but different role (for example, admin or editor). The goal is to conv ...

Best practices for using useEffect to fetch data from an API_FETCH in a certain condition

When retrieving state from an API using Zustand within a useEffect function, what is the recommended approach to do so? Currently, my implementation is quite straightforward: export interface ModeState{ modes: Mode[]; fetchModes: () => void; } expo ...

Getting and passing data from a frontend form to Java, then displaying it back in the frontend through Angular

The successful implementation of a payment verification SOAP XML API in JAVA has been achieved. Through the use of JAVA code, XML requests are sent to a payment API with SOAPAction headers and Body, resulting in a response from the API. Now, the goal is t ...

Steps for displaying API Response in a material-table

In my project, I have a component named List which displays data using mat-cards. When a specific mat-card is clicked, it navigates to another component called home. In this home component, the data from the selected mat-card is displayed within another ma ...