javascript - Angular 7 中的动态验证: enable() 和 setValidators 取决于更改触发的标志
问题描述
我的上一个 Angular 项目是很久以前的事了,同时我也在使用 VueJS。现在我回来并在 Angular 7 中实现了一个带有一些条件字段的反应式表单。
我下面的解决方案有效,我可以启用字段或设置验证器依赖于标志。但不知何故我不喜欢这个解决方案,它太长而且不直观。没有人能凭直觉知道,您必须禁用某个字段才能禁用验证器。Angular/TypeScript 专家可以帮助我优化该代码或以正确的方式进行吗?
onChangeType(scope: string) {
console.log(scope);
this.myForm.get('riskType').disable();
this.myForm.get('chancheType').disable();
if (scope === 'local') {
this.flags.isScopeLocal = true;
this.flags.isScopeTemplate = false;
this.flags.isScopeGlobal = false;
this.myForm.get('chancheType').enable();
this.myForm.get('chancheType').setValidators(Validators.required);
} else if (scope === 'template') {
this.flags.isScopeTemplate = true;
this.flags.isScopeLocal = false;
this.flags.isScopeGlobal = false;
this.myForm.get('riskType').enable();
this.myForm.get('riskType').setValidators(Validators.required);
} else {
// global
this.flags.isScopeLocal = false;
this.flags.isScopeTemplate = false;
this.flags.isScopeGlobal = true;
this.myForm.get('riskType').disable();
this.myForm.get('chancheType').disable();
}
}
简短说明:如果范围是本地或模板,则将有一个新的必填字段。如果范围是全局的,则此字段消失,其验证器将被停用。
解决方案
使用指令补充我的评论如何使禁用的反应形式在 Angular2 中可编辑
孤独的是,您不需要使用 setValidators 更改验证器,并且该指令是启用/禁用控件的人。我认为更“可读”
<input formControlName="riskType" [enabledControl]="scope=='local'">
<input formControlName="chancheType" [enabledControl]="scope=='template'">
myForm=this.fb.group({
riskType:['',Validators.required],
cacheType:['',Validators.required],
})
推荐阅读
- javascript - Svelte 过渡:如何使传入的“输入”动态 Svelte 组件过渡等待传出的“输出”Svelte 组件完成
- java - Android 通知 - 用另一个通知替换一个通知
- gensim - 为海量数据集加速 Gensim 的 Word2vec
- uml - 在 UML 中,如何调用为其构建状态图的对象?
- angular - 根据所选选项显示字段 - 反应式表单
- css - 使文本随背景更改为新颜色,例如视差背景
- html - HTML 在 div 标签中包含没有额外空格的文本
- jax-rs - 如何在 JAX-RS ContainerRequestFilter 中获取路径模板?
- c++ - 在 VS2019 项目中集成 ImageMagick:x64-windows-static 库
- mongodb - 如何在微服务架构中将默认数据播种到 Mongo db(或任何数据库)?