我正在以角4反应形式实施验证。我的表格是这样的
app.component.html中的验证码代码在这里
<label>Email
<input type="text" formControlName="userEmail">
</label>
<div class="alert"
*ngIf="rForm.controls['userEmail'].hasError('required') &&
rForm.controls['userEmail'].touched">Email is required</div>
<div class="alert"
*ngIf="rForm.controls['userEmail'].hasError('email') &&
rForm.controls['userEmail'].touched">Enter valid email</div>
问题是,当我离开“电子邮件字段为空”时,两个验证器同时显示为
但我希望如果用户将“电子邮件”字段留空,那么只显示所需的验证程序,如果用户输入错误的语法,则语法验证程序应显示 我怎样才能做到这一点?
答案 0 :(得分:0)
怎么样?
<div class="alert"
*ngIf="rForm.controls['userEmail'].hasError('required') &&
rForm.controls['userEmail'].touched">Email is required</div>
<div class="alert"
*ngIf="!rForm.controls['userEmail'].hasError('required') && rForm.controls['userEmail'].hasError('email') &&
rForm.controls['userEmail'].touched">Enter valid email</div>
答案 1 :(得分:0)
使用ngIf
尝试其他 <label>Email
<input type="text" formControlName="userEmail">
</label>
<div class="alert"
*ngIf="(rForm.controls['userEmail'].hasError('required') &&
rForm.controls['userEmail'].touched); else formatError">Email is required</div>
<ng-template #formatError >
<div class="alert"
*ngIf="rForm.controls['userEmail'].hasError('email') &&
rForm.controls['userEmail'].touched">Enter valid email</div>
</ng-template>