Angular2表单如何获取特定错误类型?

时间:2016-06-08 15:44:22

标签: forms angular

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

<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&#39; s表单有效,否则我得到一个&#34;类型错误的js错误:无法读取属性&#39; minlength&#39; of null&#34;

这让我觉得错误集合是空的,我如何得到特定的错误?

供参考我使用: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>

谢谢!

3 个答案:

答案 0 :(得分:5)

使用安全导航(猫王)操作员

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

如果未报告任何错误,则name.errorsnull,因此name.errors.minlength会抛出。

答案 1 :(得分:0)

这适用于RC4,使用新表格&#39;模块&#39;。

<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

工作,我的单元测试失败了..

&#34; exportAs&#34;没有指令设置为&#34; ngModel&#34;

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

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

答案 2 :(得分:-1)

你可以这样做:

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

.pristine:控件的值已更改
.valid:控件的值有效

文档示例:angular.io forms