0

I have a reactive form which contain a list of checkboxes and if one of them is checked an input form will be displayed. How can I add a validator to ensure that at least one checkbox should be selected.

This is my component.ts :

coveragestypes : Array<ItemPolicyModel>= 
[{id:'1', name :'type 1'},
{id : '2',name :'type 2'},
{id : '3',name :'type 3'},
{id:'4',name:'type 4'}]

      coveragesObject : any = null;
       policyForm = new FormGroup({
         coveragesObject : new FormArray([])
        })
     ngOnInit() {
          this.addCheckboxes();
      }
      addCheckboxes() {
    let formGroups: FormGroup[] = this.coveragestypes.map(coverage => {
      return new FormGroup({
         id: new FormControl(coverage.id),
         name: new FormControl(coverage.name),
         value: new FormControl("", Validators.pattern(/^-?(0|[1-9]\d*)?$/)),
         checked: new FormControl(false)
      });
     });
     this.coveragesObject =  new FormArray(formGroups);
     this.policyForm.setControl('coveragesObject', this.coveragesObject );
     }

And this is my component.html :

    <div *ngFor="let coverage of coveragesObject.controls;let i = index; ">
    <div [formGroup]="coverage">
       <input type="checkbox" kendoCheckBox [formControl]="coverage.controls.checked" />
       {{coverage.controls.name.value}}        
      <ng-container *ngIf="coverage.controls.checked.value">
          <input type="text" [formControl]="coverage.controls.value" style="  height: 100%;max-height:10px;padding : 0.5rem 0.75rem; 
                                            border-color: rgba(0, 0, 0, 0.125);width: 40%;">
         <span style="position: absolute;padding : 0.05rem 0.25rem ;">£</span>
         <div *ngIf="coverage.controls.value.invalid"
              style="font-size: xx-small; color : red">
         {{ "newRepair.intake.policyInfo.ownrisk" | translate }}
         </div>
    </ng-container>
</div>
</div>

Can anyone help me, please?

1
  • Did my answer solve your problem? Commented Feb 4, 2021 at 18:33

1 Answer 1

1

The thing you are looking for is custom form validator. Angular provides us with the option of creating and passing validator functions that will be triggered on form changes.

Lets say for simplicity we have a FormArray containing FormControl-s with boolean values, that represent checkboxes, the thing that we should do is as follows

...
// Our form
form = new FormGroup({
    boxes: new FormArray(
      [],
      // Pass custom validator that will check if the array has one element with value `true` a.k.a. at least one checked
      c => {
        const atLestOneChecked = (c as FormArray).controls.find(
          x => x.value === true
        );
        if (atLestOneChecked) {
          return {};
        }
        return { error: true };
      }
    )
 });
 ...
 ngOnInit(){
    // Populate form
    new Array(10).fill(null).forEach(() => {
      (this.form.get("boxes") as FormArray).push(new FormControl(false));
    });
 }

So what had i done here is passing a function as second argument to the new FormArray(), this function will be called each time when there are changes related to the FormArray references and based on the check if there is any FormControl with value true inside of the FormArray i am atachinng or clearing the erroros associated with the FormArray.

Ther few important things that i didnt discussed but you need to know when creating validators:

First you should always return error object Second you can pass a single validator or an Array of validators Third if you need async validators (for example validation based on BE response) you need to use the AsyncValidators

Here is a working stackBlitz

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.