Clearing error messages from a form using the reset button or after cancelling the form

I am having trouble removing the error outline around the input box and error messages displayed below it. When I cancel the form or click on the reset button, the input fields' content along with the error messages should be cleared. However, currently, only the input fields are being cleared while the error messages remain.

  • My current method for clearing the fields is using this.formname.reset(), but it does not clear the error messages.
  • I am working with Angular 7.

TypeScript file

loginForm: FormGroup;
 validation() {
        this.loginForm = this.formBuilder.group({
            userName: ['', Validators.required],
            password: ['', Validators.required]
        });
    }
 clearFields() {
          this.loginForm.reset();
          this.validation()
    }

HTML code

<form #formDirective="ngForm" [formGroup]="loginForm" (ngSubmit)="onSubmit()">
            <div class="form-group">
                <label for="username">Username</label> <input type="text"
                    formControlName="userName" class="form-control"
                    placeholder="User name"
                    [ngClass]="{ 'is-invalid': submitted && f.userName.errors }" />
                <div *ngIf="submitted && f.userName.errors" class="invalid-feedback">
                    <div *ngIf="f.userName.errors.required">Username is required</div>
                </div>
            </div>
            <div class="form-group">
                <label for="password">Password</label> <input type="password"
                    formControlName="password" class="form-control"
                    [ngClass]="{ 'is-invalid': submitted && f.password.errors }"
                    placeholder="Password" />
                <div *ngIf="submitted && f.password.errors" class="invalid-feedback">
                    <div *ngIf="f.password.errors.required">Password is required</div>
                </div>
            </div>
            <div class="form-group text-center">
                <button class="btn btn-primary" (click)="onSubmit();">Login</button>
                &nbsp;
                <button type="button" class="btn btn-light"
                    (click)="clearFields();">cancel</button>
            </div>
        </form>

Answer №1

Aside from the response by Sivaramakrishnan, it would be beneficial to review this answer related to a previous inquiry on the same topic.

Answer №2

It appears you are calling the function this.validation() within the clearFields() method. Please consider removing that line to streamline your code.

clearFields() {
          this.loginForm.reset();
          this.validation()
    }

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

Tips for saving metadata about properties within a class

I am looking to add metadata to properties within classes, specifically using abbreviations for property names. By using annotations like @shortName(abbreviated), you can label each property as follows: function shortName(shortName: string){ return fu ...

Why async functions don't require a 'then' keyword

There are two functions that produce the same outcome: const p1 = async () => { return 1; }; const p3 = new Promise((resolve, reject) => { resolve(1); }); console.log(typeof p1.then); console.log(typeof p3.then); It is surprising that both fu ...

Guide to configuring a function to display the maximum value on a boxplot in Highcharts

I'm currently using Angular in combination with the highcharts boxplot API. While I am aware that I can manually set the max value of the y-axis in the chart configuration, such as: max: 100, tickInterval: 10. There's now a need for me to dynami ...

Ways to implement debounce in handling onChange events for input fields in React

I've been attempting to implement debounce functionality in my React app without relying on external libraries like lodash or third-party node modules. I've tried various solutions found online, but none have worked for me. Essentially, in the h ...

Data has not been loaded into the Angular NGX Datatable

As a beginner in Angular, I am struggling to set data from the module. ngOnInit() { this.populate(); } public populate() { this.productService.getAllProduct('6f453f89-274d-4462-9e4b-c42ae60344e4').subscribe(prod => { this. ...

Combining Data in Angular and Firestore: Exploring the Power of Observables

I am attempting to retrieve a profile document using valueChanges and combine it with session data. However, when I utilize forEach, the observable returned is null (I'm still new to both technologies). The following code successfully re ...

"Exploring the relationship between Vue checkbox components: parent and

Currently, I am working on a checkbox group where the behavior is such that if the parent checkbox is checked, all the child checkboxes will also be checked. Similarly, if a child checkbox is checked, the parent checkbox should also get checked, and so on. ...

What is the best way to indicate a particular element within a subdocument array has been altered in mongoose?

I have a specific structure in my Mongoose schema, shown as follows: let ChildSchema = new Schema({ name:String }); ChildSchema.pre('save', function(next){ if(this.isNew) /*this part works correctly upon creation*/; if(this.isModifi ...

Having trouble with downloading a zipped folder on the client side in an Angular and Node.js (MEAN) application

I am facing an issue with allowing users to download compressed folders from the server. I have successfully compressed the folder, however, when attempting to read the tar file and send it for download on the client side, the file is either corrupted or o ...

I'm looking to find the Angular version of "event.target.value" - can you help me out?

https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/pages/home/home.component.html I am currently working on getting the dropdown menu to function properly for filtering the flags displayed below it. My initial thought was to replicate the search ...

Troubleshooting: Angular 6 issue - Unable to toggle visibility using ngIf

I am currently learning Angular and I'm working on the app.component.html as shown below: <app-login *ngIf="!loggedIn"></app-login> <section *ngIf="loggedIn" style="background:#EBF0F5;"> <div class="container"> ...

Can you explain the concept of injection context within Angular version 16 and later?

I have come across the term "Injection context" and am trying to understand what it entails. In Angular, there are several things that are connected to injection context: EnvironmentInjector#runInContext injectionContext runInInjectionContext inject() Fr ...

What is the best way to obtain a signed cookie in aws-sdk-js-v3?

I am looking to utilize signed cookies for accessing private content stored on S3 using CloudFront for CDN. I am struggling to identify the appropriate commands to generate signed cookies in aws-sdk-js-v3. According to the updated SDK documentation, it sh ...

What is the best way to retrieve the href attribute when working with cheerio?

Is there a way to retrieve the link using Cheerio in this code snippet? <div class="someClass"> <a href="someLink">Link</a> </div> I attempted to do so, but unfortunately it was unsuccessful. let link = $(&a ...

It appears that the functions in linqts are not clearly defined

Currently, I am in the process of learning Angular4 and facing challenges with getting linqts to function properly. Within my room-list.component.ts file, I include it in this manner: import { List } from 'linqts'; A few lines below, I have my ...

Debugging Typescript code with line numbers

When opening the console in a browser, typically the javascript line number of a function call or error message is displayed. However, my current setup involves using TypeScript, which gets compiled to Javascript. I am wondering if there is a way to retr ...

Troubleshooting routing: The Location.path() function consistently returns an empty string

I stumbled upon this tutorial which seems to be the most up-to-date example for testing routing. I'm eager to incorporate mock components in my testing strategy eventually. Unfortunately, when trying out the provided plunker, I encountered some issues ...

Angular progress tracker with stages

I have been exploring ways to create a progress bar with steps in Angular 12 that advances based on the percentage of progress rather than just moving directly from one step to another. This is specifically for displaying membership levels and indicating h ...

In Angular, what is the best way to change the format of the timestamp '2019-02-22T12:11:00Z' to 'DD/MM/YYYY HH:MM:SS'?

I am currently working on integrating the Clockify API. I have been able to retrieve all time entries from the API, which include the start and end times of tasks in the format 2019-02-22T12:11:00Z. My goal is to convert the above date format into DD/MM/Y ...

The reloading feature in Angular components is not functioning as intended

I am looking for a way to refresh the component without having to refresh the entire page. Below is the code snippet that I have been using: import { Component, VERSION, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from &apos ...