在角7动态验证:使()&取决于标志setValidators通过改变触发

问题描述 投票:1回答:1

我最后的角项目是很久以前的事,我已经与VueJS同时工作。现在我回来了并实施了反应形式与角7一些有条件的领域。

我下面的作品的解决方案,我可以启用字段或设置验证dependend上的标志。但不知何故,我不喜欢这样的解决方案,它是太长,不直观。没有人能凭直觉,你必须禁用字段来禁用验证。一个角/打字稿高手可以帮我优化的代码或做正确的方式?

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();
    }
} 

简短的说明:范围是本地或模板将有一个新的必填字段。如果范围是全局然后消失这一领域及其验证将被停用。

javascript angular typescript optimization angular-reactive-forms
1个回答
1
投票

使用指令How to make a disabled reactive form Editable in Angular2补充我的评论

孤独的,你不需要改变使用setValidators的验证,而指令是启用/禁用控制谁。我认为更“可读”

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

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

})
© www.soinside.com 2019 - 2024. All rights reserved.