我有包装输入字段的组件.在组件中,我从@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函数.
现在模板中的代码将是:
(可选的)
希望它能帮到你,蒂埃里
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。