Home > Enterprise >  Reactive Form reset and forms validation
Reactive Form reset and forms validation

Time:10-07

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

CodePudding user response:

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

  • Related