使用Angular 6指令或组件,在输入无效等情况下向容器div中添加has-error类的最简单的防错解决方案是什么。
<div class="form-group m-form__group has-error"> // add has-error here.
<label> Email address </label>
<input type="email" class="form-control m-input" formControlName="email">
<span class="m-form__help"> Email is required. </span>
</div>
答案 0 :(得分:1)
猜测您将form
用作formGroup
,即:<form [formGroup]="form">
您可以通过以下方法检查电子邮件是否有误:form.get('email').invalid
,当输入内容脏或被触摸时,您可能需要显示错误:
直接代码:
<div class="form-group m-form__group" [ngClass]="form.get('email').invalid && (form.get('email').dirty || form.get('email').touched)"> // add has-error here.
<label> Email address </label>
<input type="email" class="form-control m-input" formControlName="email">
<span class="m-form__help"> Email is required. </span>
</div>
更好的方式:
例如:
<div class="form-group m-form__group" [ngClass]="displayCssFor('email')"> // add has-error here.
<label> Email address </label>
<input type="email" class="form-control m-input" formControlName="email">
<span class="m-form__help"> Email is required. </span>
</div>
和打字稿:
displayCssFor(field: string|Array<string>) {
return (this.form.get(field).invalid && (form.get(field).touched || form.get(field).dirty) ) ? 'has-error' : '';
}