0
votes

I know this question is asked many times before. i want to reset my form and validation after submit. i used formGroup to create a form. i used a button for submit the form if the form is valid i reset the form by using form.reset() it clear the fields but not the error i also try to use

this.form.markAsPristine();
this.form.markAsUntouched();
this.form.updateValueAndValidity();

to reset the form validation but it didint work

from the code given below i can reset the form but the input fields remain dirty or touched as a result input field marked as red. can someone suggest me what is best practice of creating a form, reset the form and validation.

my html code is

    <mat-form-field class="example-full-width" appearance="outline" style="width: 100%;">   
        <input type="text" matInput formControlName="title" placeholder="Enter Module Title" #message maxlength="50">
        
        <mat-error *ngIf="form.controls.title.hasError('required') && (form.controls.title.dirty || form.controls.title.touched)">
          Module Title is <strong>required</strong>
        </mat-error>
      </mat-form-field>

  <button (click)="save()"> Save</button>

this is my .TS file

@ViewChild('my2Form', { static: false }) my2Form!: NgForm;

    this.form = this.fb.group({
      title: ['',[Validators.required]],
    });

   save()
     { if(this.form.invalid)
      { this.form.markAllAsTouched();
         return;
       }
     else
      {
      this.my2Form.resetForm();
      this.form.markAsPristine();
      this.form.markAsUntouched();
      this.form.updateValueAndValidity();
      this.form.markAsPristine();
        }

enter image description here

1
disable save button until formGroup is invalid instead of markAllasTouched - navnath
i want to show the user that he/she misses these fields so i cant disable the button - Abhishek Agarwal
I sthis what you need? stackblitz.com/edit/… - navnath
please use angular material matinput and 2-3 fields you will get the error i.e after reset input field marked as red - Abhishek Agarwal
If you create stackblitz for your problem, it will be easy for me to help you - navnath

1 Answers

0
votes

In template just add type=button :

<button type="button" (click)="save()">Save</button>

In component.ts

if (this.form1.invalid) {
    this.form1.markAllAsTouched();
} else {
    this.form1.reset();
}

Angular demo