Skip to content

mat-form-field does not remove mat-form-field-invalid class on FormGroup reset #4190

Open

Description

@Nathan-Ryan

Bug, feature request, or proposal:

Bug

What is the expected behavior?

Upon resetting a FormGroup, I would expect the visual state of the form to be reset also.

What is the current behavior?

The form group and controls are reset but the mat-input-invalid class remains on the md-input-container suggesting that the control is invalid.

What are the steps to reproduce?

This only seems to happen when the [formGroup] attribute is on a form tag. Works as expected on a div tag.

Create component with a FormGroup and a FormControl with Validators.required .
Create a form tag with the [formGroup] attribute.
Add an input control to the form with a required attribute.

When running, fill out the form so its valid, then reset the form and model through the click handler on a button. The required control will now have the mat-input-invalid class.

Which versions of Angular, Material, OS, browsers are affected?

Angular 4.0.1
Material 2.0.0-beta.3
Windows 10
Chrome 57

Activity

  1. changed the title [-]md-input-container does not remove mat-input-invalid class on FromGroup reset[/-] [+]md-input-container does not remove mat-input-invalid class on FormGroup reset[/+] on Apr 21, 2017
  2. kurpav commented on Apr 22, 2017

    @kurpav

    Have the same issue 😢

  3. self-assigned this
    on Apr 26, 2017
  4. added
    P3
    on Apr 26, 2017
  5. mmalerba commented on May 10, 2017

    @mmalerba
    Contributor
  6. mmalerba commented on May 11, 2017

    @mmalerba
    Contributor

    It looks like this is just a matter of putting type="reset" on your button. Without it, the form is marked as submitted which causes the error styling to show up. see: http://plnkr.co/edit/IUhbPom8FnauivHUW3bU?p=preview

  7. goelinsights commented on May 12, 2017

    @goelinsights

    @mmalerba trying to understand how this would fix the issue for a button already type="submit".

    I'm resetting after the form is submitted and a response has been received back from the server in an observable complete block.

    i.e.,
    submitForm()
    .subscribe(
    res => store.dispatch(type: foo, res),
    e => log(e),
    () => form.reset()); <- still leaving the form inputs as invalid

  8. mmalerba commented on May 12, 2017

    @mmalerba
    Contributor

    @goelinsights sounds like maybe a forms issue (could be related to angular/angular#15741). The md-input-container logic is correct, so there's nothing for material to do here

  9. zpydee commented on May 13, 2017

    @zpydee

    @mmalerba not sure i agree with your diagnosis. I am experiencing same issues and have only updated from material-beta2 to material-beta3. Main angular libraries remain unchanged and problem has only been introduced since material upgrade.

    It looks like this is just a matter of putting type="reset" on your button. Without it, the form is marked as submitted which causes the error styling to show up.

    after form is submitted, error styling should definitely be removed.

  10. jeroenvanagt commented on May 30, 2017

    @jeroenvanagt

    @mmalerba Why is this issue closed? The problem still exists when reseting the formGroup like explained by @goelinsights

    Scenario:
    Press submit button
    Do some stuff with the data
    Then call formGroup.reset()

    formGroup.reset() does NOT remove mat-input-invalid class
    screen shot 2017-05-30 at 4 06 33 pm

  11. willshowell commented on May 30, 2017

    @willshowell
    Contributor

    @jeroenvanagt try this

    <form [formGroup]="myFormGroup" #f="ngForm">
      ...
    </form>
    @ViewChild('f') myNgForm;
    
    reset() {
      this.myNgForm.resetForm();
    }

    http://plnkr.co/edit/sRCiYvRqGevK493w79A4?p=preview

  12. jeroenvanagt commented on May 31, 2017

    @jeroenvanagt

    @willshowell,

    I understand that a reset button works. However, in my case I want to use a submit button, send the data to the backend server and then reset the form (so a new invite can be created).

    For the reset, I use :
    this.form.reset()
    where form is a formGroup

  13. jeroenvanagt commented on May 31, 2017

    @jeroenvanagt

    I now use the following workaround

            this.form.reset()
    
            Object.keys(this.form.controls).forEach(key => {
              this.form.controls[key].setErrors(null)
            });
    
    
  14. 52 remaining items

  15. BrutalCSkakan commented on Jan 11, 2022

    @BrutalCSkakan

    Still facing this issue, reset() wont reset the validation.

    resetForm() on the directive doesn't solve my issue, however the Object.keys setErrors above works.. Which is redundant as f*** for all of my different components.

  16. Burtan commented on Mar 8, 2022

    @Burtan

    I'm also facing this error.

  17. mrmokwa commented on Mar 9, 2022

    @mrmokwa

    Anybody knows if the new form (v14) fix this issue?

  18. paradox37 commented on Mar 15, 2022

    @paradox37

    The solution is simple here. Add this to your module:

    export class CustomMaterialFormsMatcher implements ErrorStateMatcher {
        isErrorState(control: FormControl | null): boolean {
            return !!(control && control.invalid && (control.dirty || control.touched));
        }
    }
    
    providers: [
        {
            provide: ErrorStateMatcher, useClass: CustomMaterialFormsMatcher
        }
    ]
    

    Then you can simply use this.form.reset(), nothing else.

  19. rajmetti commented on May 6, 2022

    @rajmetti

    In v13 , setting button type as "button" worked for me.

  20. danielHin commented on Sep 1, 2022

    @danielHin

    Hey everyone

    Anything new?

    Still need to call .setErrors() on the certain form field to get it back into pristine state after resetting the whole form group in v13

    this.myFormGroup.get('label').setErrors(null);

  21. ApplY3D commented on Nov 24, 2022

    @ApplY3D
    Contributor

    The solution is simple here. Add this to your module:

    export class CustomMaterialFormsMatcher implements ErrorStateMatcher {
        isErrorState(control: FormControl | null): boolean {
            return !!(control && control.invalid && (control.dirty || control.touched));
        }
    }
    
    providers: [
        {
            provide: ErrorStateMatcher, useClass: CustomMaterialFormsMatcher
        }
    ]
    

    Then you can simply use this.form.reset(), nothing else.

    The best solution if you want to reset the form as a side-effect (like after http request), thank you!

    Material ErrorStateMatcher bind on form.submitted - source.
    So, for multiple submitting, you should provide different error matcher.

    Possible (great) solutions - #4190 (comment)

  22. saimyousuf commented on May 21, 2023

    @saimyousuf

    It looks like this is just a matter of putting type="reset" on your button. Without it, the form is marked as submitted which causes the error styling to show up. see: http://plnkr.co/edit/IUhbPom8FnauivHUW3bU?p=preview

    Perfect example of Occam's Razor: The simplest explanation is always the best.

  23. petogriac commented on Apr 25, 2024

    @petogriac

    2024 and I need to still look for a workaround to this? :(

  24. jpangburn commented on Jun 2, 2024

    @jpangburn

    What works in 2024 with the least extra code

    With Angular 18 and reactive forms and standalone components and Material 3, the one that still seems to work is to setup your form like newGateForm = this.formBuilder.group({... then in your submit handler after you've done your submit work:

        // reset the form
        this.newGateForm.reset();
        // this hack is needed to clear any validation errors that are still showing
        // really Angular? 7 years and no clean solution?
        Object.keys(this.newGateForm.controls).forEach(key => {
          //@ts-ignore
          this.newGateForm.controls[key].setErrors(null);
        });
    

    The //@ts-ignore is because you're probably also using TypeScript in a new project and it doesn't like that line. I tried this on Chrome and Safari, both worked. I like this one because there's no changes to the HTML template, just the submit processing code so it keeps the mess contained to one dirty spot on the rug.

    What also works

    You can also do:

    <form [formGroup]="myForm" #formDirective="ngForm" (ngSubmit)="submitForm(formDirective)">
    and

    private submitForm(formDirective: FormGroupDirective): void {
        formDirective.resetForm();
        this.myForm.reset();
    }
    

    I kind of like this one because it's clear that the reset takes two steps working on two different parts of the form system, though it's still a workaround for a single form reset. The downside is the mess is spread to both the HTML template and the submit processing code.

    What doesn't work

    There were a number of ideas that probably worked in the past that I tried that do not seem to work today:

    • <form novalidate... this would have been nice but doesn't seem to help.
    • <button type="reset" or <button type="button" this prevents your users from using the Enter key to submit forms. Users on non-touch devices will despise you for doing this. Do not do this. Always use <button type="submit" as the submit button on a form.
    • <div [formGroup]="form" same problem as reset. Don't do this to your users.
    • (ngSubmit)="onSubmitFunction($event)"> followed by the submit handler calling event.currentTarget.reset(). At least on my system, currentTarget was null so this didn't work.
    • @ViewChild(FormGroupDirective) myForm; then this.myForm.resetForm(). TBH, I didn't really understand how to use this, and the plunker was old enough that it didn't work. It might work if you knew how that directive was supposed to tie to your form.
  25. ph360 commented on Aug 31, 2024

    @ph360

    I thinked that the problem was I. This error is a lot of complex. I see that if in the button use type="Submit" when type script registerForm.reset() execute the validation and show errors but if button is type="Reset" or (click)=funcion() the type script ejecuta registerForm.reset() without problem. Someone presented one solutión that do the thing good but don't know if is best practic.

    `<form [formGroup]="registerForm" (submit)="submitF($event)">

    submitF(event:any){
    event.currentTarget.reset();
    this.addressForm.reset();
    }`

    This should be more easy the implement of shape nativa.

  26. ph360 commented on Aug 31, 2024

    @ph360

    My solution was create two buttons one whit submit for send information and other for reset the data of form.

    <button mat-raised-button color="accent" type="submit" [disabled]="!registerForm.valid" i18n>Create new account</button> <button mat-raised-button type="Reset" i18n>Reset</button>

    this not is one solution elegant but for moment work well

  27. asevila commented on Nov 22, 2024

    @asevila

    jpangburn

    The thing is that wath @jpangburn suggest is basically wath should do with the form from the formBuilder. Why is not doing it ? I think it's redundant, but it's necessary to doit, because in the other way, it does not work correctly.

  28. Ben555555 commented on Mar 23, 2026

    @Ben555555

    What works in 2024 with the least extra code

    With Angular 18 and reactive forms and standalone components and Material 3, the one that still seems to work is to setup your form like newGateForm = this.formBuilder.group({... then in your submit handler after you've done your submit work:

        // reset the form
        this.newGateForm.reset();
        // this hack is needed to clear any validation errors that are still showing
        // really Angular? 7 years and no clean solution?
        Object.keys(this.newGateForm.controls).forEach(key => {
          //@ts-ignore
          this.newGateForm.controls[key].setErrors(null);
        });
    

    The //@ts-ignore is because you're probably also using TypeScript in a new project and it doesn't like that line. I tried this on Chrome and Safari, both worked. I like this one because there's no changes to the HTML template, just the submit processing code so it keeps the mess contained to one dirty spot on the rug.

    What also works

    You can also do:

    <form [formGroup]="myForm" #formDirective="ngForm" (ngSubmit)="submitForm(formDirective)"> and

    private submitForm(formDirective: FormGroupDirective): void {
        formDirective.resetForm();
        this.myForm.reset();
    }
    

    I kind of like this one because it's clear that the reset takes two steps working on two different parts of the form system, though it's still a workaround for a single form reset. The downside is the mess is spread to both the HTML template and the submit processing code.

    What doesn't work

    There were a number of ideas that probably worked in the past that I tried that do not seem to work today:

    • <form novalidate... this would have been nice but doesn't seem to help.
    • <button type="reset" or <button type="button" this prevents your users from using the Enter key to submit forms. Users on non-touch devices will despise you for doing this. Do not do this. Always use <button type="submit" as the submit button on a form.
    • <div [formGroup]="form" same problem as reset. Don't do this to your users.
    • (ngSubmit)="onSubmitFunction($event)"> followed by the submit handler calling event.currentTarget.reset(). At least on my system, currentTarget was null so this didn't work.
    • @ViewChild(FormGroupDirective) myForm; then this.myForm.resetForm(). TBH, I didn't really understand how to use this, and the plunker was old enough that it didn't work. It might work if you knew how that directive was supposed to tie to your form.

    For me the first workaround will hide the errors but on a new submission the validation rules will be ignored and the formgroup will always be valid.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3area: material/form-field

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions