区分值无效和Angular2控件中未给出的值

时间:2016-12-01 10:28:13

标签: validation angular

我有一个只接受数字的控件,我想给用户一个提示,为什么控件被标记为红色:

<label>Version</label>
<input name="version" #version="ngModel" required type="number" pInputText [(ngModel)]="item.version"/>
<small class="field-validation-error" [hidden]="version.valid">
  Not a number
</small>

问题是,当控件中没有值时会显示消息。这是无效的,但我希望显示“价值是必需的”#39;消息然后。我试过了:

    <small class="field-validation-error" [hidden]="version.value">
      Value is required
    </small>

然后,需要&#39;值&#39;如果提供了值,则显示消息,但不是数字。

如何使用ngModel绑定区分值not not和value,但无效?

2 个答案:

答案 0 :(得分:1)

怎么样:

<label>Version</label>
<input name="version" #version="ngModel" pattern="[0-9]*" required type="number" pInputText [(ngModel)]="item.version"/>

<small class="field-validation-error" *ngIf="version.control.dirty && version.control.hasError('required')">
    Value is required
</small>

<small class="field-validation-error" *ngIf="version.control.dirty && version.control.hasError('pattern')">
    Not a number
</small>

答案 1 :(得分:0)

我会选择

  <small class="field-validation-error" [hidden]="item.version.value">
      Value is required
    </small>

只需检查实际值而不是输入元素的值