Clear Angular FormControls after save without form errors

I have the following code:

initializeForm(): void {
    this.myForm = new FormGroup({
        name: new FormControl('hello world', Validators.required)
    });
}

clearValues(): void {
    // save my form.. or do something, then clear my form
    this.myForm.patchValue({ name: null });
}

And then in my html I have the input and some button to save changes. After that I call clearValues.

<input type=text formControlName="name">
<button (click)="clearValues()">Save</button>

When I start my app, the field has no red errors so I can type everything, but If I leave it empty, red errors appears (obviously).

If I write something such as 'Hello World' and I save. The input becomes empty and the red errors appears.

I tried with markAsTouched() or markAsDirty but the same results happens.

How I can click the button and leave the input without errors?

This is what I get, I want an empty with no errors input.

enter image description here

Upvotes: 0

Views: 1453

Answers (2)

I ended up doing this:

this.myForm.reset();
Object.keys(this.myForm.controls).forEach(key => {
    this.myForm.controls[key].setErrors(null);
});

Working this way. Thank you all.

Upvotes: 1

Ploppy
Ploppy

Reputation: 15353

There is a function for this on the form object.

this.myForm.resetForm();

Upvotes: 0

Related Questions