如果給定字段爲空,太短或太長,我試圖隱藏/顯示相應的錯誤消息。這裏是我的表格的一部分: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