0

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

2
  • your html should have a a <form> tag with (submit)="clearValues()", while the button can be just: <button type="submit">.... Then it's enough to call this.myForm.reset() in your submit function to clear it Commented Dec 30, 2020 at 15:17
  • The error still appear because the FormControl it has "Validators.required" so when the .reset() calls, the input becomes empty and the error appears because is required. Commented Dec 30, 2020 at 15:26

2 Answers 2

1

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.

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

Comments

0

There is a function for this on the form object.

this.myForm.resetForm();

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.