After a long break from my last Angular project, during which I worked with VueJS, I have returned and successfully implemented a reactive form with conditional fields in Angular 7. However, I feel that my current solution is overly lengthy and not very intuitive. It requires disabling a field in order to disable validators, which may not be immediately apparent to others looking at the code. I am hoping for guidance from an expert in Angular/TypeScript to help me optimize this code or suggest a better approach.
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();
}
}
In brief, when the scope is set to local or template, a new required field appears. If the scope is changed to global, this field disappears and its validator is deactivated.