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.