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.
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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…