我无法清除输入框周围的错误轮廓以及输入框下方的错误消息。当我取消表单或单击重置按钮时,它必须清除输入字段和错误消息的内容,但只能清除错误消息不会被清除的内容。
TS文件
loginForm: FormGroup;
validation() {
this.loginForm = this.formBuilder.group({
userName: ['', Validators.required],
password: ['', Validators.required]
});
}
clearFields() {
this.loginForm.reset();
this.validation()
}
HTML代码
<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>
答案 0 :(得分:0)
再次调用功能this.validation()
,从clearFields()
功能中删除该行
clearFields() {
this.loginForm.reset();
this.validation()
}
答案 1 :(得分:0)
除了Sivaramakrishnan的答案外,您可能还想check this answer回答之前提出的类似问题。