加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 10:20:38 所属栏目:安全 来源:网络整理
导读:我有包装输入字段的组件.在组件中,我从@Input()inputControl:Control;接收Control对象.在模板中,我有span,如果不需要组件中的输入字段,则显示消息. span class="input-label-caption" (optional)/span 和输入 input *ngIf="inputMode=='text' || inputMode=
我有包装输入字段的组件.在组件中,我从@Input()inputControl:Control;接收Control对象.在模板中,我有span,如果不需要组件中的输入字段,则显示消息.
<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对象?
我想知道我是否可以像这样使用它

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

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

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

编辑

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

这是相应的代码:

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

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

现在模板中的代码将是:

(可选的)

希望它能帮到你,蒂埃里

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读