3

I am using a reactive form:

<form
  #f="ngForm"
  class="form"
  [formGroup]="registerForm"
  (ngSubmit)="onSubmit()"
  novalidate
>
  <div class="title-box-form">
    <strong>Company Information</strong>
    <div class="row">
      <div class="form-group col-12">
        <input
          type="text"
          class="form-control pink-border"
          placeholder="Company Name"
          formControlName="company_name"
        />
      </div>
      <span
        class="text-danger"
        *ngIf="
          (registerForm.get('company_name').touched || submitted) &&
          registerForm.get('company_name').errors?.required
        "
      >
        company name is required
      </span>
    </div>
  </div>
  <div class="form-group col-12">
    <input
      type="text"
      class="form-control pink-border"
      placeholder="Email Address"
      formControlName="email"
    />
  </div>
  <span
    class="text-danger"
    *ngIf="
      (registerForm.get('email').touched || submitted) &&
      registerForm.get('email').errors?.required
    "
  >
    email name is required
  </span>
  <span
    class="text-danger"
    *ngIf="
      registerForm.get('email').touched &&
      registerForm.get('email').errors?.email
    "
  >
    Enter a valid email address
  </span>
  <div class="modal-footer">
    <input type="submit" class="btn-blue" />
    <mat-spinner *ngIf="loading"></mat-spinner>
  </div>
</form>

After submitting I want to reset the form in the submit function in the component.ts file I am doing

onSubmit() {
    this.submitted = true;
    if (this.registerForm.valid) {
      this.loading=true;
      
     let values = JSON.stringify(this.registerForm.value);
     //this.registerForm.reset();
     this.form.reset();
    this.form.markAsPristine();
    this.form.markAsUntouched();
    this.form.updateValueAndValidity();
}

I am using:

export class ManageCustomerComponent implements OnInit {
@ViewChild('f') form;

I tried reserform() and markAsPristine but all of them triggers the validation errors after resetting the form I need to reset the form after submit and if show the validation again after the form submit I am importing this at the top of my page:

import { Component, OnInit, ViewChild , ChangeDetectorRef } from '@angular/core';   
import {SidebarComponent} from '../sidebar/sidebar.component';
import {HeaderComponent} from '../header/header.component';
import { ModalDirective } from 'ngx-bootstrap/modal';

import { Validators, FormGroup, FormBuilder,FormControl,FormGroupDirective,NgForm } from     '@angular/forms';
import {ServerService} from '../server.service';
import { Router } from '@angular/router';
import { HttpClient, HttpParams } from '@angular/common/http';
import Swal from "sweetalert2"

validation

Below is the full component TS-code:

import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { SidebarComponent } from '../sidebar/sidebar.component';
import { HeaderComponent } from '../header/header.component';
import { ModalDirective } from 'ngx-bootstrap/modal';

import {
  Validators,
  FormGroup,
  FormBuilder,
  FormControl,
  FormGroupDirective,
  NgForm,
} from '@angular/forms';
import { ServerService } from '../server.service';
import { Router } from '@angular/router';
import { HttpClient, HttpParams } from '@angular/common/http';
import Swal from 'sweetalert2';

declare var $: any;

@Component({
  selector: 'app-manage-customer',
  templateUrl: './manage-customer.component.html',
  styleUrls: ['./manage-customer.component.css'],
})
export class ManageCustomerComponent implements OnInit {
  @ViewChild('f') form;
  registerForm: FormGroup;
  submitted = false;
  loading = false;
  onSubmit() {
    this.submitted = true;
    if (this.registerForm.valid) {
      this.loading = true;

      let values = JSON.stringify(this.registerForm.value);
      this.server
        .request('POST', '/company/store', {
          company_name: this.registerForm.value.company_name,
          company_email: this.registerForm.value.email,
          company_phone: this.registerForm.value.phone,
          company_phone1: this.registerForm.value.phone1,
          company_fax: this.registerForm.value.fax,
          company_parish: this.registerForm.value.parish,
          company_city: this.registerForm.value.city,
          company_person_title: this.registerForm.value.salutation,
          company_person_first_name: this.registerForm.value.first_name,
          company_person_last_name: this.registerForm.value.last_name,
          company_person_email: this.registerForm.value.email2,
          company_person_phone: this.registerForm.value.work_phone,
          company_person_mobile: this.registerForm.value.mobile_phone,
        })
        .subscribe(
          (data) => {
            this.loading = false;

            Swal.fire({
              position: 'top-end',
              icon: 'success',
              title: 'Company added succesfully',
              showConfirmButton: false,
              showCloseButton: true,
            });
            console.log(data);
            //        let elem = document.getElementById('close2');
            //
            //let evt = new MouseEvent('click', {
            //        bubbles: true,
            //        cancelable: true,
            //        view: window
            //    });
            //
            //elem.dispatchEvent(evt);
            //this.registerForm.reset();

            //this.form.form.reset();
            //this.form.form.markAsPristine();
            //this.form.form.markAsUntouched();
            //this.form.form.updateValueAndValidity();
            this.form.resetForm();
          },
          (error) => {
            this.loading = false;
          }
        );
    }
  }

  constructor(
    private fb: FormBuilder,
    private server: ServerService,
    private http: HttpClient,
    private changeDetectorRef: ChangeDetectorRef
  ) {
    this.registerForm = this.fb.group({
      company_name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      phone: ['', Validators.required],
      phone1: [''],
      fax: [''],
      parish: [''],
      city: [''],
      mailing_address: [''],
      salutation: [''],
      first_name: [''],
      last_name: [''],
      email2: [''],
      work_phone: [''],
      mobile_phone: [''],
    });
  }

  ngOnInit(): void {}
  ngAfterViewInit() {
    $('.select-custom').selectpicker();
  }
}

11
  • are you using a updateOn: 'submit' for updating form control values? Commented Oct 27, 2020 at 6:12
  • @at-in No I am just using a simple submit and reset Commented Oct 27, 2020 at 6:14
  • can you share you whole component.ts file? Commented Oct 27, 2020 at 6:16
  • try this.form.form.markAsPristine();this.form.form.markAsUntouched();this.form.form.updateValueAndValidity(); Commented Oct 27, 2020 at 6:53
  • or form.resetForm(); Commented Oct 27, 2020 at 6:55

1 Answer 1

1

well there may be other ways too, but as I see you are using a submitted boolean you can set that to false after you have submitted your form data to the server and used resetForm in your API subscribe function

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.