且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-29 08:42:52

你可以试试用这个表达:

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.

现在模板中的代码是:

(可选的)

希望对你有帮助蒂埃里