typescript – 检查输入控件是否在angular2中具有某种类型的vallidator

前端之家收集整理的这篇文章主要介绍了typescript – 检查输入控件是否在angular2中具有某种类型的vallidator前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有包装输入字段的组件.在组件中,我从@Input()inputControl:Control;接收Control对象.在模板中,我有span,如果不需要组件中的输入字段,则显示消息.
  1. <span
  2. class="input-label-caption">
  3. (optional)
  4. </span>

和输入

  1. <input
  2. *ngIf="inputMode=='text' || inputMode=='email'"
  3. type="{{inputMode}}"
  4. [ngFormControl]="inputControl"
  5. placeholder="{{placeholder}}"
  6. class="input-text"
  7. [disabled]="inputDisabled"
  8. [ngClass]="{
  9. 'inverted': inverted
  10. }">

如果包含Validators.required,我如何读取表单inputControl对象?
我想知道我是否可以像这样使用它

  1. <span
  2. class="input-label-caption"
  3. *ngIf="!inputControl.validators.required"
  4. >
  5. (optional)
  6. </span>
您可以尝试使用此表达式:
  1. <span
  2. class="input-label-caption"
  3. *ngIf="!inputControl.errors?.required"
  4. >
  5. (optional)
  6. </span>

errors属性包含每个失败的验证器名称的一个条目.

我使用Elvis运算符作为errors属性,因为如果没有验证错误,它可以是未定义的.

编辑

在您发表评论之后,我认为您可以使用带有Validators.required函数的===运算符直接检查“必需”验证器.事实上,验证器只是一个函数,Validators.required函数用于“必需”验证.

这是相应的代码

  1. this.hasrequiredValidator = (this.inputControl.validator === Validators.required);

在validator属性是数组的情况下,您需要扩展一下测试以检查数组中是否存在Validators.required函数.

现在模板中的代码将是:

(可选的)

希望它能帮到你,蒂埃里

猜你在找的Angularjs相关文章