我最后的角项目是很久以前的事,我已经与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();
}
}
简短的说明:范围是本地或模板将有一个新的必填字段。如果范围是全局然后消失这一领域及其验证将被停用。
使用指令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],
})