我有包装输入字段的组件.在组件中,我从@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>
我使用Elvis运算符作为errors属性,因为如果没有验证错误,它可以是未定义的.
编辑
在您发表评论之后,我认为您可以使用带有Validators.required函数的===运算符直接检查“必需”验证器.事实上,验证器只是一个函数,Validators.required函数用于“必需”验证.
这是相应的代码:
在validator属性是数组的情况下,您需要扩展一下测试以检查数组中是否存在Validators.required函数.
现在模板中的代码将是:
(可选的)
希望它能帮到你,蒂埃里