简体   繁体   中英

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.

在此处输入图像描述

There is a function for this on the form object.

this.myForm.resetForm();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM