检查输入控件是否在 angular2 中具有某种类型的验证器 [英] Check if input control has certain type of vallidator in angular2

查看:26
本文介绍了检查输入控件是否在 angular2 中具有某种类型的验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有包装输入字段的组件.在组件中,我从 @Input() inputControl: Control; 接收 Control 对象.在模板中,如果不需要组件中的输入字段,我有显示消息的跨度.

I have component that wraps input field. In the component i receive the Control object from @Input() inputControl: Control;. In the template i have span that shows message if input field in the component is not required.

<span
  class="input-label-caption">
  (optional)
</span>

和输入

<input
    *ngIf="inputMode=='text' || inputMode=='email'"
    type="{{inputMode}}"
    [ngFormControl]="inputControl"
    placeholder="{{placeholder}}"
    class="input-text"
    [disabled]="inputDisabled"
    [ngClass]="{
    'inverted': inverted
    }">

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

How can i read form inputControl object if it contains Validators.required? I want to know if i can used it like this for example

<span
  class="input-label-caption"
  *ngIf="!inputControl.validators.required"
  >
  (optional)
</span>

推荐答案

你可以试试用这个表达:

You can try to use this expression:

<span
  class="input-label-caption"
  *ngIf="!inputControl.errors?.required"
>
  (optional)
</span>

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

The errors attribute contains one entry per name of validator that failed.

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

I use the Elvis operators for the errors attribute since it can be undefined if there is no validation error.

编辑

根据您的评论,我认为您可以使用 === 运算符和 Validators.required 函数直接检查必需"验证器.事实上,验证器只是一个函数,Validators.required 函数用于必需"验证.

Following your comment, I think that you can check a "required" validator using the === operator with the Validators.required function directly. In fact a validator is simply a function and the Validators.required function is used for "required" validation.

这里是对应的代码:

this.hasRequiredValidator = (this.inputControl.validator === Validators.required);

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

In the case where the validator attribute is an array, you need to extend a bit the test to check if the Validators.required function is present in the array.

现在模板中的代码是:

(可选的)

希望对你有帮助蒂埃里

这篇关于检查输入控件是否在 angular2 中具有某种类型的验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆