After Resetting the Angular-Material Form mat-error reappears

58 Views Asked by At

I hope someone can help me, I have created a form using FormControl using Angular Material, In that Form After Submitting i have used reset method to reset the Form , Even then after resetting the form i am getting mat-error from my form. It showing mat-error message even after making the FormControl property markAllFieldsAsUntouched as true.

Component.html

Below is my HTML Code for the input form filed

<mat-form-field>
         
          <mat-label>Select a SO</mat-label>
          <input matInput placeholder="Select a SO" [formControl]="SOController" [matAutocomplete]="SOAuto">

          <mat-autocomplete #SOAuto="matAutocomplete" (optionSelected)="onOptionSelectedSO($event)">
            <mat-option *ngFor="let sO of filteredSO" [value]="sO.soName">{{sO.soName}}</mat-option>
          </mat-autocomplete>
          <div *ngIf="(SOController.touched) && (SOController.invalid)" class="text-danger">
            <mat-error *ngIf="SOController.hasError('required')"><small>*SO Name is required</small></mat-error>
          </div>
        </mat-form-field>
<mat-form-field>
          <mat-label>Select a Candidate</mat-label>
          <mat-select id="candidateId" name="candidateId" formControlName="candidateId">
            <mat-option *ngFor="let candidate of CandidateData" value="{{candidate.candidateId}}">
              {{candidate.candidateUid}}/{{candidate.candidateName}}</mat-option>
          </mat-select>
          <div *ngIf="(f.candidateId.touched) && (f.candidateId.invalid)" class="text-danger">
            <mat-error *ngIf="f.candidateId.errors?.['required']"><small>*CandidateName is
                required</small></mat-error>
          </div>
        </mat-form-field>

To submit the above filed i am using the below submit button

<button mat-raised-button color="primary" (click)="onSubmit()">Submit</button>

Component.ts

Below is My FormControl

mapppingForm = new FormGroup({
    candidateId: new FormControl('', [Validators.required]),
    sowId: new FormControl('', [Validators.required]),
    soName: new FormControl('', [Validators.required]),
    statusId: new FormControl('', [Validators.required]),
    mappingDate: new FormControl('', [Validators.required])
  })

  get f() { return this.mapppingForm.controls; }

  SOController = new FormControl('', [Validators.required]);

  filteredSO: any[] = [];

onSubmit() {
    console.log(this.mapppingForm.value)

    this.mapppingForm.value.mappingDate = formatDate(this.mapppingForm.value.mappingDate as string, 'yyyy-MM-dd', this.locale);
    this.submitted = true;
    console.log(this.mapppingForm)
    if (this.mapppingForm.invalid) {
      this.markAllFieldsAsUntouched();

      return;
    }
    else {
      console.log(this.mapppingForm)
      this.onAdd();

    }
  }


  isFieldInvalid(fieldName: string): boolean {
    const control = this.mapppingForm.get(fieldName);
    return control !== null && control.invalid && (control.touched || this.submitted);
  }

In the Below Method I am Adding the Values to MY DB after Adding the data i am resetting my FormControl And i am making the Form as Untouched

onAdd() {
    let formValue = this.mapppingForm.value;
    let obj = {
      sowId: formValue.sowId,
      candidateId: formValue.candidateId,
      StatusId: formValue.statusId,
      mappingDate: formValue.mappingDate,
      type: "post",
    };
    this.service.PostCandidateMappingData(obj).subscribe(data => {
      console.log(data)
      this.openSnackBar(data, 'Ok')
      this.mapppingForm.reset();
      this.SOController.reset();
      this.markAllFieldsAsUntouched();

    })
  }

markAllFieldsAsUntouched() {
    Object.keys(this.mapppingForm.controls).forEach(fieldName => {
      this.mapppingForm.controls[fieldName as keyof typeof this.mapppingForm.controls].markAsUntouched();
    });
  }

After resetting the Object I am getting the mat-error in the form fields.Can anyone suggest me a way to resolve this.

1

There are 1 best solutions below

2
On

Please update the function

markAllFieldsAsUntouched() {
    this.SOController.markAsUntouched();
    Object.keys(this.mapppingForm.controls).forEach(key => {
        this.mapppingForm.get(key).markAsUntouched();
    });
    // if still facing issues try to add the below code!
    this.SOController.updateValueAndValidity();
    this.mapppingForm.updateValueAndValidity();
}

If you still face this issue, please check the errors and ensure that you are checking the touched field before showing the error message!