Search code examples
angularformsreset

Why after empForm.reset(); the required fields marked as invalid error?


i'm learning Angular Form. here is a simple form, has ename/job/sal fields, ename/job are required. BEFORE i submit, when i input values, the validators are working fine, and clear function also nicely erase the filled text. BUT, AFTER i click submit (which invokes empForm.reset()), the required fields marked as red color - invalid fields error, the clear button also cannot remove the red color, i think it's not a reasonable behavior. i only want after submit, the fields are all stay originally without failed validation red marks. how to achieve that, thanks.

Thanks & Regards, Martin.

<form [formGroup]="empForm" (ngSubmit)="onSubmit()">
    <div class="fields-container">
        <mat-form-field>
            <input formControlName="ename" matInput placeholder=Ename>
            <mat-error *ngIf="empForm.controls['ename'].errors?.required">Ename is required.</mat-error>
        </mat-form-field>
        <mat-form-field>
            <input formControlName="job" matInput placeholder=Job>
            <mat-error *ngIf="empForm.controls['job'].errors?.required">Job is required.</mat-error>
        </mat-form-field>
        <mat-form-field>
            <input formControlName="sal" matInput placeholder=Salary>
        </mat-form-field>
    </div>
    <div class="buttons-container">
        <button mat-raised-button type="submit" [disabled]="empForm.invalid">Submit</button>
        <button mat-raised-button type="button" (click)="onClear()">Clear</button>
    </div>
</form>

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-emp',
  templateUrl: './emp.component.html',
  styleUrls: ['./emp.component.scss']
})
export class EmpComponent implements OnInit {
  empForm;
  constructor(private fb: FormBuilder) {
    this.empForm = this.fb.group({
      ename: ['', Validators.required],
      job: ['', Validators.required],
      sal: [1000]
    })
  }

  ngOnInit(): void {
  }

  onSubmit(){
    // save to db - TBD
    this.empForm.reset();
  }


  onClear(){
    this.empForm.reset();
  }

}

Solution

  • I think its known issue, as a workaround you can try:

    HTML:

    <form [formGroup]="empForm" #f="ngForm">
      ...
    </form>
    

    TS:

    @ViewChild('f') myNgForm;
    
    onSubmit() {
      // Service call
      this.myNgForm.resetForm();
    }
    

    Working_Demo