In Angular 5, when you reset a required form control in a reactive form, the required error message beneath the input field is not cleared

Within my template, there is a form that becomes visible when a button is clicked-

     <form [formGroup]="person"
          (ngSubmit)="onSubmitNewPerson()"
          #formDirective="ngForm">

            <mat-form-field>
                <input matInput formControlName="firstName" required>
            </mat-form-field>

            <mat-form-field>
                <input matInput formControlName="lastName" #last required>
            </mat-form-field>
</form>

My component contains the following code-

  @ViewChild('formDirective') formDirective: FormGroupDirective;

 this.person = this.formBuilder.group({
            lastName: ['', Validators.required],
            firstName: ['', Validators.required]
        });

Upon closing the form, I execute this function-

   this.formDirective.resetForm();//hack that I saw in some question
    this.person.reset();

However, when I reopen the form, I notice an immediate red error under the input field.

I have also attempted the following-

    this.person.get('firstName').markAsUntouched();
   this.person.get('lastName').markAsUntouched();
     this.person.get('firstName').markAsPristine();
    this.person.get('lastName').markAsPristine();

Unfortunately, this solution did not work either.

Does anyone have any ideas on how to resolve this issue?

Answer №1

There was a time when I needed to reset the validators, so I utilized the code below:

    this.person.get('firstName').clearValidators();
    this.person.get('firstName').updateValueAndValidity();

Answer №2

To make changes to your HTML template, simply remove the "required" attribute. If you want to show different error messages on focus out, you can try the following:

Here is the HTML template:

<div class="form-group">
        <label for="name" class="form-control-label">
        *Amount:
        </label>
        <input type="number" name="amount" class="form-control"  [formControl]="form.controls['amount']">
        <div>
        <small *ngIf="form.controls['amount'].hasError('required') && form.controls['amount'].touched" class="text-danger">
           Please enter an amount.
        </small>
        <small  *ngIf="form.controls['amount'].hasError('min') && form.controls['amount'].touched" class="text-danger">
             Your amount must be at least 0.01.
        </small>
        <small  *ngIf="form.controls['amount'].hasError('max') && form.controls['amount'].touched" class="text-danger">
                Your amount cannot exceed 999999.99.
        </small>
        </div>

And here is the component.ts file:

 import { FormGroup, FormBuilder, Validators} from '@angular/forms';

constructor(private fb: FormBuilder) {  }

this.form = this.fb.group({
    amount: [null, Validators.compose([Validators.required, Validators.min(0.01), Validators.max(999999.99)])],
  });

Answer №3

While this question may be dated, The answer provided could be useful for those facing a similar issue.

For those encountering this problem with the Angular material mat-stepper, the solution can be found in response to this question.

(This is why some individuals may have struggled to replicate the issue)

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

Discovering a method to recover information obtained through intercepting an observable

I am currently working on an Angular 6 cli application where a component utilizes a service to fetch data. As part of my project, I am incorporating an ngrx store into the application. I am considering abstracting the interactions with the store within the ...

Using SimplyJS and XML: extracting the value of a specific key

Hey there, I wanted to update you on my progress with the Pebble Watch project. I've switched over to using an official external API to make HTTP requests for values, and now I'm receiving results in XML format instead of JSON. Here's a ...

When a const variable is declared within the composition-api setup(), it remains unchanged unless redeclared within the function scope

Being primarily a back-end developer, the front-end side of things is still relatively new to me. I'm aware that there are concepts in this domain that I haven't fully grasped yet, and despite my efforts, I'm unable to resolve a particular i ...

Extract the canvas code line from a function without using the eval function

Greetings, fellow Stackers! Please pardon my formatting as this is my debut question on this platform. I am currently working on a basic vector drawing tool. If you want to view the full CodePen code for reference, feel free to click here. Here's t ...

What is the reasoning behind leaving out wwwroot from tsconfig?

Currently, I am working on a TypeScript project using an ASP.NET 5 template in VS.NET 2015. In the scripts/tsconfig.json file that I added, there is a default exclude section which includes: "exclude": [ "node_modules", "wwwroot" ] However, a ...

I'm seeking clarification on the composition of Objects in Node.js

After running a console.log on a parameter from the callback function in the Node.js formidable package, here is the output of files: { fileUpload: [ PersistentFile { _events: [Object: null prototype], _eventsCount: 1, _maxListene ...

typescriptIn React Router v5 with TypeScript, an optional URL parameter is implemented that can have an undefined

I'm currently working with react-router v5.1 and TypeScript, and I have set up the following route configurations: <Router basename="/" hashType="slash"> <Switch> <Route path="/token/:tokenName"> <TokenPag ...

Error message encountered when attempting to export functions in Reactjs, resulting in an undefined function error in the context of Reactjs

As I work on creating an adaptive menu using Reactjs and Material UI, I have managed to complete everything. However, I encountered an issue when trying to import a const defined in a different file as the functions are not functioning as expected. The fu ...

How can two unique links toggle the visibility of divs with two specific IDs?

I am developing an interactive questionnaire that functions like a 'create your own adventure' story. The questions are shown or hidden depending on the user's responses. Below is the HTML code: <!-- TIER 3 ============================== ...

Adjusting data points on a radar chart.js through user interaction

I have a radar map generated using chart.js, along with some input fields where users can enter values that I want to reflect in the graph. I am exploring ways to update the chart dynamically as the user types in the values. One option is to have the char ...

Is Angular's Http Module classified as middleware?

As I delve into the world of middleware, I've encountered a bit of a challenge trying to fully grasp its concept. Currently, I'm exploring the ExpressJS documentation and its explanation of a middleware function: "Middleware functions are functi ...

I'm looking for a streamlined method to simultaneously access multiple APIs with GraphQL and React

For my client side project, I'm using GraphQL and React but opting not to use Redux for state management. Instead, I have organized my API calls into custom hook files as shown below: const [getSomeData, { data: getSomeDataData, loading: getSomeData ...

Live tweet moderation made easy with the Twitter widget

Currently in search of a widget, jQuery plugin, hosted service, or equivalent that can be easily integrated into an HTML page. This tool should display and automatically update live tweets featuring a specific hashtag, only from designated accounts set by ...

A guide on Implementing PastBack Functionality with AJAX Responses

When I make a GET request for an HTML page, I come across the following element: <a id="ctl00_cphRoblox_ClaimOwnershipButton" href="javascript:__doPostBack('ctl00$cphRoblox$ClaimOwnershipButton','')">Claim Ownership</a> My ...

Implementing server-side validation measures to block unauthorized POST requests

In my web application using angular and node.js, I am in the process of incorporating a gamification feature where users earn points for various actions such as answering questions or watching videos. Currently, the method involves sending a post request t ...

Is it possible for a Node.js server to specifically generate dynamic HTML, with Nginx handling the distribution of static data, and then automatically deliver the content to the client?

After primarily working with Apache and PHP, I've recently started exploring Nginx and Node.js and have been really enjoying the experience. Initially, I set up an Express server to handle website files and HTML rendering using Handlebars. However, I ...

How come the hidden container does not reappear after I click on it?

I'm having an issue with a hidden container that holds comments. Inside the container, there is a <div> element with a <p> tag that says "Show all comments". When I click on this element, it successfully displays the comments. However, cli ...

Tips for transferring <form> information to an object array within a React application

I am currently working on a basic component that takes an input message, displays it in a list below the input field when submitted. However, I am facing an issue where clicking the submit button only results in a blank bullet point appearing below. impo ...

Attributes of the host element in Angular 1.5 components

I am seeking a way to customize attributes on the host element for Angular 1.5 components. What is the purpose? I would like to assign a class to a component in order to apply specific styles. For example, if the parent component has display: flex set, ...

Using Material UI Slider along with Typescript for handling onChange event with either a single number or an

Just diving into Typescript and encountered an issue with a Material UI Slider. I'm trying to update my age state variable, but running into a Typescript error due to the typing of age being number and onChange value being number | number[]. How can I ...