Search code examples
angularjsangularangular-materialangular-validation

Alternate checkbox selection conditionally for formgroup controls


I have a formgroup called fruits created

 fruits: FormGroup = formBuilder.group({      
      numberOfFruits: [0,Validators.min(0)],
      apple: false,
      mangoes: false
    });

and the html is as follows:

<div formGroupName="fruits">
    <div>
        <p>Key in the number of fruits you want to select</p>
    </div>
    <div>
        <input readonly matInput formControlName="numberOfFruits" type="number">
    </div>
    <mat-checkbox formControlName="apple">Apple</mat-checkbox>
    <mat-checkbox formControlName="mangoes">Mangoes</mat-checkbox>
</div>

I would want to perform validation as follows:

  1. If 0 number of fruits is selected then do not allow selection of any(apple/mangoes)checkbox.
  2. If 1 is selected for number of fruits then allow only/at least one checkbox to be selected (either apple/mango)
  3. If 2 or more is selected for total number of fruits, atleast 1 checkbox (apple/mangoes/both) to be selected.

I have created a validation for the group fruits by writing individual conditions as follows:

if (group.controls['numberOfFruits'].value === 1 || (group.controls['numberOfFruits'].value == 2 &&
        group.controls['apple'].value === true)) {
    group.controls['mangoes'].patchValue(false);
}
if (group.controls['numberOfFruits '].value == 1 || (group.controls['numberOfFruits'].value == 2 && group.controls['mangoes'].value === true)) {
    group.controls['apple'].patchValue(false);
}

Is there a better and effective way to achieve this?


Solution

  • I think is better subscribe to group.valueChanges (remember you need subscribe after create the formGroup). Some like

    group.valuesChange.subscribe(res=>{
       if (res.numberOfFuits>=1)
       {
          ..enable apple and mangos..
          if (res.numberOfFuits==1)
          {
             if apple, mangos=false; //<--remember {emitEvent:false}
             if mangos, apple=false
          }
       }
       else
       {
          disable apple and mangos and set value to false;
       }
    })
    

    And you need make a custom formValidation to control when numberOfFruits>2