I am having trouble removing the error outline around the input box and error messages displayed below it. When I cancel the form or click on the reset button, the input fields' content along with the error messages should be cleared. However, currently, only the input fields are being cleared while the error messages remain.
- My current method for clearing the fields is using this.formname.reset(), but it does not clear the error messages.
- I am working with Angular 7.
TypeScript 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>