Search code examples
angulartypescriptmean-stackangular-reactive-formsangular-forms

Angular form controls validating based on radio button selection


I have a form where some field will be shown in case that a question is answered YES.Thus, those form controls has to be validated if the answer is YES. but what happen in my form is that, the form become Invalid if I do not have those field filled. here is my code:

 <label for="DSYesNo"><h3> Does you need to access other Data? </h3> </label>
      <div *ngFor="let obj of yesNoArray">
        <input type="radio"  class="form-control" name="DSYesNo"  value="{{obj}}"  formControlName="DSYesNo"  (change)="DSYesNO(obj)">
        {{obj}}
      </div>

      <div *ngIf='allDSflag'> // allDSflag by default is false.
       
        <div form="form-group">
          <label for="allDS"><h3> Data Subject Category: </h3> </label>
          <div [ngClass]="{
            'has-errors': ((primaryForm.controls.allDS.errors (primaryForm.controls.allDS.dirty || primaryForm.controls.allDS.touched)) ),
            'has-success': (!primaryForm.controls.allDS.errors)  }">

            <div *ngFor="let DScategory of allDataSubjects">
              <input type="checkbox"
                     formControlName="allDS"
                     name="allDS"
                     (click)="onOtherDataSubjectClick(DScategory)"
              >
              {{DScategory.category}}
            </div>
  
            <!--Validations-->
            <ul class="help-block">
              <li *ngIf="primaryForm.controls.allDS.errors?.requiredTrue &&
                  (primaryForm.controls.allDS.dirty || primaryForm.controls.allDS.touched)">This field is required</li>
            </ul>
          </div>

Here is where I check the selcted value of the radio to set the flag.

  DSYesNO(value) {
    console.log(value);
    if (value=="Yes") {
      this.allDSflag = true
    } else
      this.allDSflag = false;
  }

here is where I create the form :

createForm() {
    this.primaryForm = this.formBuilder.group({

        DSYesNo: [],
    
        allDS:['', Validators.compose([
          Validators.requiredTrue
        ])],
        justifyOtherDS: ['', Validators.compose([
          Validators.required
        ])]
        }

here is the submit bottn which has to be disable as far as the form is invalid:

 <input  type="submit"  class="btn btn-primary" [disabled]="((!primaryForm.valid) && !allDSflag)" value="Submit" />

could you please help me understand what makes the button always DISABLE. Anyone?


Solution

  • if you want to validate field based on the value of other field you can subscribe on ValueChanges Observable of field and then set or unset validators.

     this.primaryForm.get('DSYesNo')
                .valueChanges
                .subscribe(value => {
    
                 const otherFiled = this.primaryForm .get('otherField');
                 if(value==='YES'){
                        otherFiled.enable();
                        otherFiled.setValidators([Validators.required]);
                 }  else {
                        otherFiled.disable()
                        otherFiled.clearValidators();
                  }
    
    
    });
    

    for disable button just check if form is valid

    <button type="submit" [disabled]="!primaryForm.valid" class="btn btn-primary ">Submit</button>