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

Using Angular 6 pipes can simplify observable operations by eliminating the need for explicit typing

Recently, I upgraded my application from Angular5 to 6. Upon completing the update, I proceeded to migrate to rxjs6, which resulted in a change in my code where I was utilizing the takeWhile method. As a result, in order to subscribe to a service, my code ...

Utilize *ngFor in Angular to extract arrays from objects

I am facing an issue with the JSON structure below: { "vt1hourlyForecast": { "processTime": [ "2019-08-23T13:00:00+0300", "2019-08-23T14:00:00+0300", "2019-08-23T15:00:00+0300" ], "temperature": [ 43, 44, ...

A guide on assigning specific (x, y) coordinates to individual IDs within the tree structure

When attempting to calculate the positions of each ID in order to arrange them hierarchically on the canvas, I encounter some challenges. Whether it's organizing them into a tree structure or multiple trees resembling a forest, one restriction is that ...

Steps for adjusting the length in the getRangeLabel function of mat paginator

@Injectable() export class MyCustomPaginatorIntl extends MatPaginatorIntl { public getRangeLabel = (page: number, pageSize: number, length: number): string => { if (length === 0 || pageSize === 0) { return `${ ...

What is the proper way to set up @Input?

I attempted to accomplish this in the following manner: @Input() data: any[] = []; Upon entering the ngOnInit lifecycle method, I notice that this.data is undefined: ngOnInit() { console.log(this.data); } Consequently, when trying to access th ...

Failed deployment of a Node.js and Express app with TypeScript on Vercel due to errors

I'm having trouble deploying a Nodejs, Express.js with Typescript app on Vercel. Every time I try, I get an error message saying "404: NOT_FOUND". My index.ts file is located inside my src folder. Can anyone guide me on the correct way to deploy this? ...

Troubleshoot: Angular hide/show feature malfunctioning

I am facing an issue where clicking on one parent element causes all parent elements to show or hide their child elements accordingly. I am relatively new to Angular 2 and would appreciate any recommendations. Below, you can see the code for the component ...

Tips for invoking a function from a JavaScript file within an Angular component

This particular query remains unanswered and pertains to AngularJS. I am seeking a solution specifically for Angular, as none of the existing answers online seem to be effective in my case. Here is an outline of my code: Columns.js export class Columns { ...

Another project cannot import the library that was constructed

I am in the process of creating a library that acts as a wrapper for a soap API. The layout of the library is structured like this: |-node_modules | |-src | |-soapWrapperLibrary.ts | |-soapLibraryClient.ts | |-types | |-soapResponseType.d.ts The libra ...

The Angular Date Picker stubbornly refuses to show dates in the format of DD/MM

Implementation of my Application import { MAT_MOMENT_DATE_ADAPTER_OPTIONS, MAT_MOMENT_DATE_FORMATS, MomentDateAdapter } from '@angular/material-moment-adapter'; import { MAT_FORM_FIELD_DEFAULT_OPTIONS } from '@angular/material/form-fie ...

Encountered an issue: The type 'Usersinterface' is not meeting the document constraints

Below is a screenshot displaying an error: https://i.stack.imgur.com/VYzT1.png The code for the usersinterface is as follows: export class Usersinterface { readonly username: string; readonly password: string; } Next, here is the code for users ...

To handle a 400 error in the server side of a NextJS application, we can detect when it

I'm facing a situation where I have set up a server-side route /auth/refresh to handle token refreshing. The process involves sending a Post request from the NextJS client side with the current token, which is then searched for on the server. If the t ...

Navigating to a pre-defined default route in Angular 2 with content

Is there a way to set a default route using the updated RC router? @Routes([{ path: '/', component: Home }]) What if I want to display a page with a non-empty path initially? For example: @Routes([{ path: '/home', component: Home } ...

Exploring i18nNext integration with antd table in React

Presently, this is the UI https://i.stack.imgur.com/CMvle.png App.tsx import "./styles.css"; import MyTable from "./MyTable"; export default function App() { const data = [ { key: "1", date: "2022-01- ...

I am encountering an issue with my code where the function this.ProductDataService.getAllProducts is not recognized when

Encountering an issue while running unit test cases with jasmine-karma in Angular 7. The error received is: ProjectManagementComponent should use the ProjectList from the service TypeError: this.ProjectManagementService.getProject is not a function If I ...

The command 'npm cache clean' is failing to work in the Angular environment when using Visual Studio Code as the integrated

npm ERROR! Starting from npm@5, the npm cache will automatically fix any corruption issues and ensure that data extracted from the cache is always valid. To verify consistency, you can use 'npm cache verify' instead. npm ERROR! npm ERROR! ...

leveraging two connected hooks

I am facing a challenge where I need to utilize two hooks that are interdependent: useHook1() provides a list of ids, and useHook2(id) is called for each id to retrieve a corresponding name. Essentially, what I aim to achieve is: const [allData, setData] ...

issue with ng2-semantic-ui: remote options not properly loading in select

public optionsLookup(query:string, initial:any): Promise<any> { return new Promise ( (resolve, reject) => /*[{ id: 1, name: 'ololo1'}, { id: 2, name: 'ololo2'}]*/ this.apiService.get('private/count ...

Guide to setting up a datePicker in a cellEditorSelector

In my grid, I want to have different editors for different rows within the same column. The ag-Grid documentation provides information on how to achieve this using colDef.cellEditorSelector as a function: link I have successfully created unique editors fo ...

The specified 'contactId' property cannot be found within the data type of 'any[]'

I am attempting to filter an array of objects named 'notes'. However, when I attempt this, I encounter the following error: Property 'contactId' does not exist on type 'any[]'. notes: Array < any > [] = []; currentNot ...