如果给定字段为空,太短或太长,我试图隐藏/显示相应的错误消息。这里是我的表格的一部分:Angular2表单如何获取特定的错误类型?
<form #applicationForm="ngForm" (ngSubmit)="saveApplication()" class="form-horizontal">
<div class="row-fluid">
<div [class.has-error]="name.touched && name.errors" class="form-group">
<label for="name" class="col-sm-2 control-label form-lbl">Name</label>
<div class="col-sm-10">
<input type="text"
class="form-control" placeholder="Name"
minlength="8" maxlength="200" required
[(ngModel)]="application.Name" ngControl="name" #name="ngForm">
<p *ngIf="name.errors.minlength" class="help-block">Name is too short, it must be at least 8 characters.</p>
<p *ngIf="name.errors.maxlength" class="help-block">Name is too long, it must be less than 200 characters.</p>
<p *ngIf="name.errors.required" class="help-block">Name is required.</p>
</div>
</div>
</div>...
如果我注释掉的段落标记的* ngIf的形式工作,否则我得到的一个js错误“类型错误:无法读取属性空的‘使用MINLENGTH’”
这使我认为错误集合为空,我如何得到具体的错误?
仅供参考我使用的是这样的:Deborah Kurata - ng-conf
的解决方案建议@peppermcknight工作。添加在ngIf以下检查解决了这个问题:
<p *ngIf="applicationForm.dirty && name.errors.minlength" class="help-block">Name is too short, it must be at least 8 characters.</p>
<p *ngIf="applicationForm.dirty && name.errors.maxlength" class="help-block">Name is too long, it must be less than 200 characters.</p>
<p *ngIf="applicationForm.dirty && name.errors.required" class="help-block">Name is required.</p>
谢谢!
该组件第一次加载时可能会发生此错误。尝试在HTML中引用表单,然后检查表单是否在ngIf内脏。 '* ngIf =“!form.dirty && name.errors.minlength' – peppermcknight