Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

javascript - Dynamic Validations in Angular 7: enable() & setValidators depending on flags triggered by changes

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Complementary my comment using a directive How to make a disabled reactive form Editable in Angular2

Lonely, you needn't change the validators using setValidators, and the directive is who enabled/disabled the controls. I think is more "readable"

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

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

})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...