1
votes

I got an Angular Reactive Form working well except when I fill all the required fields and I press Chrome's back button (after submitting it or not) and go back to the form page again. My form is still filled but I can't submit the form again. I guess it's because the form validation is invalid, I have to re fill every field in order to press the submit button again.

How can I force the re validation of the form so I don't have to erase and type everything again?

  profileForm = this.fb.group({
    checkbox: [false],
    checkbox_cgv: [false, Validators.requiredTrue],
    firstName: ['', Validators.required],
    lastName: ['', Validators.required],
    email:['', [Validators.required, Validators.email]],
    phoneNumber:['', Validators.required],
    billing: this.fb.group({
      address1: ['', Validators.required],
      address2: [''],
      city: ['', Validators.required],
      zip: ['', Validators.required]
    }),
    shipping: this.fb.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      address1: ['', Validators.required],
      address2: [''],
      city: ['', Validators.required],
      zip: ['', Validators.required]
    }),
  });

Part of the html file:

<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
    <div class="row">
      <div class="col">
        <p class="form-row form-left">
          <span class="input-wrapper">
            <input type="text" class="form-control" formControlName="firstName" required>
          </span>
        </p>
        <p class="form-row form-right">
          <span class="input-wrapper">
            <input type="text" class="form-control" formControlName="lastName" required>
          </span>
        </p>
...

<button type="submit" class="btn btn-primary order-btn" [disabled]="!profileForm.valid">Order</button>
2

2 Answers

0
votes

You can reset the form on either ngOnInit or ngAfterViewInit but make sure this reset come after your form init

ngAfterViewInit() {
  //reset form controls
  this.profileForm.reset();

  //reset validators, explicitly
  this.accountForm.setErrors(null)

}

if reseting the whole form doesn't affect the nested groups/arrays target them as this.profileForm.controls['billing'].reset();

0
votes

I recommend to try using

profileForm.resetForm()