Search code examples
angularangular-forms

Angular Form reset issue


I am new in Angular and I have a FromGroup:

inputData: FormGroup;

.....

this.inputData = this.formBuilder.group({
        vorname: ['', [Validators.required]],
        nachname: ['', [Validators.required]],
        ort: ['', [Validators.required]],
        anschrift: ['', [Validators.required]],
        geburtsdatum: ['', [Validators.required]],
        gueltigAb: ['', [Validators.required]]
    });

And I have a button to clear the form content with this method:

protected onClearFormContent() {
    this.inputData.reset();
}

Now, when I click the button, the input data from the form get cleared but since all the controls are mandatory, the form looks like this:

enter image description here

I do not want my input fields marked as invalid because of the empty content, since the whole form has been reloaded.

After searching for a while, I have founded this solution:

protected onClearFormContent() {
    this.inputData.reset();
    Object.keys(this.inputData.controls).forEach(key => {
        this.inputData.controls[key].setError(null);
    });
}

But then the validation does not work later on, and it does not matter if I leave one of the mandatory fields empty, it does not get marked as invalid.

I tried to play with touched / untouched values, but did not help.

Can please somebody help how to solve this?

Thanks a lot in advance!


SOLUTION

Ok, so, the solution from @ammad-hassan worked like a charm. I only needed to change my button from:

<button mat-button (click)="onClearFormContent()">Formular leeren</button>

To:

<button mat-button type="submit">Formular leeren</button>

And calling my function like this:

(ngSubmit)="onClearFormContent()"

Solution

  • try calling this.inputData.markAsUntouched(); instead of setting errors to null after resetting your form. Moreover, instead of this.inputData.reset() try calling this.userForm.resetForm(). to make this accessible- declare form as NgForm like this:

    @ViewChild("userForm") userForm: NgForm;
    

    and in your template

    <form #userForm="ngForm" (ngSubmit)="onSaveUser()" novalidate>
        ....
    </form>