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.
我下面的解决方案有效,我可以启用字段或在标志上设置验证程序dependend.但是我不喜欢这种解决方案,因为它太长且不直观.没有人可以理解,您必须禁用一个字段才能禁用验证器. 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.
推荐答案
使用指令孤独地,您不需要使用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屋!