gpt4 book ai didi

typescript - 检查输入控件是否在angular2中具有某种类型的验证器

转载 作者:太空狗 更新时间:2023-10-29 17:24:31 24 4
gpt4 key购买 nike

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

<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,我该如何读取它?我想知道我是否可以像这样使用它

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

最佳答案

你可以尝试使用这个表达式:

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

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

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

编辑

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

对应的代码如下:

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

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

现在模板中的代码将是:

(选修的)

希望对你有帮助,蒂埃里

关于typescript - 检查输入控件是否在angular2中具有某种类型的验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34859870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com