angular - 将多个输入参数分配给 Angular Validator
问题描述
我的 Angular 8 项目中有一个一次性自定义验证器,用于根据另一个输入的值确定是否需要输入。
@Directive({
selector: '[appRequiredExplanation]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: RequiredHardshipDirective,
multi: true
}
]
})
export class RequiredExplanationDirective implements Validator {
@Input('appRequiredExplanation') otherValue = '';
validate(control: AbstractControl): { [key: string]: any } | null {
return this.otherValue === MyComponent.needsExplanationReason &&
control.value === ''
? { required: { value: control.value } }
: null;
}
}
当前@Input
的otherValue
是第一个单选组的表单值。MyComponent.needsExplanationReason
是一个静态属性,包含需要附加信息的第一个单选组的值。
我现在有另一个具有相同范例的组件,我想通过@Input
为该静态属性创建另一个来使其可重用。
现在,我在我的 HTML 中像这样访问它:
<textarea
name="mainReasonExtraInfo"
placeholder="Please provide additional information"
[(ngModel)]="model.mainReasonExtraInfo"
appRequiredExplanation="model.mainReason"
></textarea>
如果我向 Validator 添加另一个,我将@Input
如何在 DOM 中提供该信息?
解决方案
Angular 文档确实涵盖了如何做到这一点。我试过谷歌搜索,但它从未出现在前两页上。
您可以简单地@Input
向指令添加另一个,然后继续向您的 DOM 元素添加更多属性。
export class RequiredExplanationDirective implements Validator {
// Providing the name here allows us to assign a value to the declaration call.
@Input('appRequiredExplanation') otherValue = '';
@Input() compareValue = '';
validate(control: AbstractControl): { [key: string]: any } | null {
return this.otherValue === this.compareValue &&
control.value === ''
? { required: { value: control.value } }
: null;
}
}
然后在您的 DOM 中将其设置为另一个属性。
<textarea
name="mainReasonExtraInfo"
placeholder="Please provide additional information"
[(ngModel)]="model.mainReasonExtraInfo"
appRequiredExplanation="model.mainReason"
compareValue="needsExplanationReason"
></textarea>
推荐阅读
- fortran - 变量不能出现在表达式中,用于数组维度和变量声明
- java - 如何自定义 Allure 报告以向 allure 状态报告添加新状态?
- sql - 借助日期字段应用滑动窗口功能
- python - python:范围类中的多个构造函数(__init__签名),怎么可能?
- css - 如何创建像 web what´s app 附加菜单这样的动画?
- c# - 我可以使用什么模式来编写 CRUD 功能?
- go - Godoc:将文档限制为项目(不是依赖项)
- angular - 带有 NGFOR 的材料扩展面板似乎锁定了我的 js 资源
- laravel - 使用 btable 将事件传输到父组件
- conda - 如何通过 Conda 安装 hla-la 包?