Angular 4模板驱动验证失败。这是一个已知问题,还是我的错误?
HTML:
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" required
[(ngModel)]="model.email" name="email" #email="ngModel" #spy>
<div>TODO remove: {{spy.className}}</div>
<div [hidden]="email.valid || email.pristine" class="alert alert-danger">
Valid email is required
</div>
</div>
组件类具有属性: model = new SignupModel(&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;);
CSS:
input:invalid:not(.ng-pristine) {
border-left: 5px solid #a94442; /* red */
}
input:valid:not(.ng-pristine) {
border-left: 5px solid #42A948; /* green */
}
首次加载页面时,您可以看到电子邮件类名称:form-control ng-untouched ng-pristine ng-invalid 由于email.pristine === true
,隐藏了警报消息当用户开始输入&#34; aa&#34;类名更改:form-control ng-dirty ng-valid ng-touching 现在由于email.valid === true隐藏了消息 但是,因为&#34; aa&#34;不是有效的电子邮件,左边框通过CSS显示为红色。
为什么当css正确地将输入解释为无效时,Angular会将email.valid视为true并设置ng-valid类?
当您删除&#34; aa&#34;时,样式类确实会更改为ng-invalid,正确解释&#34; required&#34;属性。
答案 0 :(得分:1)
解决方案是在输入标记中添加额外的“email”属性:
<input type="email" class="form-control" id="email" required email
[(ngModel)]="model.email" name="email" #email="ngModel">