Reputation: 6262
Using Angular 6 here with reactive form.
I have few controls on my page with submit and reset button. All the controls have required field validation on them. When the user clicks the submit button all the controls should be selected. On clicking the reset button I want to reset all the controls to their initial state.
Below is the html of one of my control:
<div class="form-group" [formGroup]="userForm">
<label class="col-md-2 control-label">Environment</label>
<div class="col-md-4" [ngClass]="{ 'has-error': userForm.hasError('required', ['environment']) && isSubmitted}">
<select class="form-control input-large" formControlName="environment">
<option value=''>-- Select --</option>
<option [ngValue]="d.Id" *ngFor="let d of data">
{{d.Name}}
</option>
</select>
<div class="invalid-feedback">
<em *ngIf="userForm.hasError('required', ['environment']) && isSubmitted">*Required</em>
</div>
</div>
</div>
Below is the reset button click in my controller:
resetClicked() {
this.createObjectForm.reset();
}
The above code works, but the issue is it also fires all the validation again so all my controls become red.
I searched and tried the below code:
Object.keys(this.createObjectForm.controls).forEach(key => {
this.userForm.get(key).clearValidators();
});
But this one works only when I click my reset button twice.
I also tried with below code, but same result :
this.userForm.markAsPristine();
this.userForm.markAsUntouched();
this.userForm.updateValueAndValidity();
Could anyone provide their inputs.
Demo: https://stackblitz.com/edit/angular-v6l2z5-eseqlr
Upvotes: 2
Views: 1636
Reputation: 214305
In order to correctly to reset reactive forms you shouldn't invent workarounds but rather use want Angular and html give you:
<form [formGroup]="userForm" #ngForm="ngForm" (ngSubmit)="onSubmit()">
<div *ngIf="... ngForm.submitted">
Show errors
</div>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</form>
Upvotes: 0
Reputation: 1931
When you reset the form the control goes back to its invalid state(it has not been choosen yet). So you need to set isSubmitted = false;
resetClicked() {
this.userForm.reset();
this.isSubmitted = false;
}
(your stackblitz helped)
And this might be better to use in the html
<em *ngIf="userForm.controls.environment.invalid && isSubmitted">*Required</em>
Upvotes: 4
Reputation: 6488
You can create a form template reference.
<form #formRef="ngForm"></form>
Access it in your component class with
@ViewChild('formRef', { static: true }) formRef;
Then you can reset the form including all validators with
this.createObjectForm.reset();
this.formRef.resetForm();
Upvotes: 0