I am unable to clear the error outline around the input box and error messages below the input box. When I canceled the form or I onclick of reset button, it has to clear the content of input fields and error messages both but its only clearing the content the error messages are not cleared.
- I am currently using this.formname.reset() which clears fileds but not error messages.
- I am using Angular7.
TS file
loginForm: FormGroup;
validation() {
this.loginForm = this.formBuilder.group({
userName: ['', Validators.required],
password: ['', Validators.required]
});
}
clearFields() {
this.loginForm.reset();
this.validation()
}
HTML code
<form #formDirective="ngForm" [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="username">Username</label> <input type="text"
formControlName="userName" class="form-control"
placeholder="User name"
[ngClass]="{ 'is-invalid': submitted && f.userName.errors }" />
<div *ngIf="submitted && f.userName.errors" class="invalid-feedback">
<div *ngIf="f.userName.errors.required">Username is required</div>
</div>
</div>
<div class="form-group">
<label for="password">Password</label> <input type="password"
formControlName="password" class="form-control"
[ngClass]="{ 'is-invalid': submitted && f.password.errors }"
placeholder="Password" />
<div *ngIf="submitted && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.required">Password is required</div>
</div>
</div>
<div class="form-group text-center">
<button class="btn btn-primary" (click)="onSubmit();">Login</button>
<button type="button" class="btn btn-light"
(click)="clearFields();">cancel</button>
</div>
</form>