Angular 7 中的动态验证:enable() &setValidators 取决于更改触发的标志 [英] Dynamic Validations in Angular 7: enable() & setValidators depending on flags triggered by changes
问题描述
我的上一个 Angular 项目是很久以前的事了,同时我一直在使用 VueJS.现在我回来了,并在 Angular 7 中实现了一个带有一些条件字段的反应式表单.
My last Angular project was a long time ago, I've worked with VueJS meanwhile. Now I am back and implemented a reactive form with some conditional fields in Angular 7.
我下面的解决方案有效,我可以启用字段或设置依赖于标志的验证器.但不知何故我不喜欢这个解决方案,它太长而且不直观.没有人能凭直觉知道您必须禁用一个字段才能禁用验证器.Angular/TypeScript 专家能否帮助我优化该代码或以正确的方式进行?
My solution below works, I can enable fields or set validators dependend on flags. But somehow I don't like this solution, it is too long and not intuitive. No one can intuit, that you have to disable a field to disable validators. Can an Angular/TypeScript expert help me to optimize that code or do it right way?
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();
}
}
简短说明:如果范围是本地或模板,则会有一个新的必填字段.如果范围是全局的,则该字段消失,其验证器将被停用.
Short explenation: If scope is local or template there will be a new reqired field. If scope is global then disappears this field and its validator will be deactivated.
推荐答案
使用指令补充我的评论 如何使禁用的反应式表单在 Angular2 中可编辑
Complementary my comment using a directive How to make a disabled reactive form Editable in Angular2
孤独,您不需要使用 setValidators 更改验证器,指令是启用/禁用控件的人.我认为更可读"
Lonely, you needn't change the validators using setValidators, and the directive is who enabled/disabled the controls. I think is more "readable"
<input formControlName="riskType" [enabledControl]="scope=='local'">
<input formControlName="chancheType" [enabledControl]="scope=='template'">
myForm=this.fb.group({
riskType:['',Validators.required],
cacheType:['',Validators.required],
})
这篇关于Angular 7 中的动态验证:enable() &setValidators 取决于更改触发的标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!