首页 > 解决方案 > 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();
    }
} 

简短说明:如果范围是本地或模板,则将有一个新的必填字段。如果范围是全局的,则此字段消失,其验证器将被停用。

标签: javascriptangulartypescriptoptimizationangular-reactive-forms

解决方案


使用指令补充我的评论如何使禁用的反应形式在 Angular2 中可编辑

孤独的是,您不需要使用 setValidators 更改验证器,并且该指令是启用/禁用控件的人。我认为更“可读”

<input formControlName="riskType" [enabledControl]="scope=='local'">
<input formControlName="chancheType" [enabledControl]="scope=='template'">

myForm=this.fb.group({
     riskType:['',Validators.required],
     cacheType:['',Validators.required],

})

推荐阅读