2016-06-08 24 views
1

如果给定字段为空,太短或太长,我试图隐藏/显示相应的错误消息。这里是我的表格的一部分: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> 

谢谢!

+1

该组件第一次加载时可能会发生此错误。尝试在HTML中引用表单,然后检查表单是否在ngIf内脏。 '* ngIf =“!form.dirty && name.errors.minlength' – peppermcknight

回答

5

使用安全导航(猫王)运算符

<p *ngIf="applicationForm.dirty && name.errors?.minlength" class="he 

当报道name.errors没有错误null因此name.errors.minlength抛出。

-1

你可以这样做:

<div [hidden]="name.valid || name.pristine" class="help-block"> 
    Name is required. 
</div> 

.pristine:控件的值发生变化
.valid:控件的值是从文档有效

例子:angular.io forms

+0

no this context to this answer -1 – danday74

0

此使用作品的RC4新形式'模块'。

<form #tagsForm="ngForm" novalidate> 
    <input name="myInput" pattern="[A-Za-z]{3}"> 
    <div [hidden]="!tagsForm.form.controls?.myInput?.errors?.pattern">Invalid pattern</div> 
</form> 

我被迫使用,因为,虽然在方法记录..

https://angular.io/docs/ts/latest/guide/forms.html

的作品,我的单元测试失败..

没有指令与“ exportAs“设置为”ngModel“

有关此错误的更多信息,请参阅...

https://github.com/angular/angular/issues/9363

相关问题