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

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

问题描述

我有包装输入字段的组件.在组件中,我从@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
    }">

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

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.

我将Elvis运算符用于errors属性,因为如果没有验证错误,则可以不确定该属性.

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.

现在模板中的代码为:

(选修的)

希望它对您有帮助, 蒂埃里

Hope it helps you, Thierry

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

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