我有包装输入字段的组件.在组件中,我从@Input()inputControl:Control;接收Control对象.在模板中,我有span,如果不需要组件中的输入字段,则显示消息.
我想知道我是否可以像这样使用它
<span class="input-label-caption"> (optional) </span>@H_403_3@和输入
<input *ngIf="inputMode=='text' || inputMode=='email'" type="{{inputMode}}" [ngFormControl]="inputControl" placeholder="{{placeholder}}" class="input-text" [disabled]="inputDisabled" [ngClass]="{ 'inverted': inverted }">@H_403_3@如果包含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>@H_403_3@errors属性包含每个失败的验证器名称的一个条目. @H_403_3@我使用Elvis运算符作为errors属性,因为如果没有验证错误,它可以是未定义的. @H_403_3@编辑 @H_403_3@在您发表评论之后,我认为您可以使用带有Validators.required函数的===运算符直接检查“必需”验证器.事实上,验证器只是一个函数,Validators.required函数用于“必需”验证. @H_403_3@这是相应的代码:
this.hasrequiredValidator = (this.inputControl.validator === Validators.required);@H_403_3@在validator属性是数组的情况下,您需要扩展一下测试以检查数组中是否存在Validators.required函数. @H_403_3@现在模板中的代码将是: @H_403_3@(可选的) @H_403_3@希望它能帮到你,蒂埃里