Uncheck all boxes in form group in angular 7

2019-07-24 02:46发布

I need to have one check box in a form group that unchecks all checkboxes in the same form group as well as keep my validation.

In my TS file i have:

 initForm() {
   this.financialSectionSix = this.formBuilder.group({
   medicaidOrSssi: [false],
   snap: [false],
   freeOrReducedPriceLunch: [false],
   tanf: [false],
   wic: [false],
   noneOfTheAbove: [false]
  });
}

In my HTML I have this:

<div [hidden]="selectedSectionGroup.sectionSix" class="tab-pane fade show 
active"
id="{{financialSectionEnum.SECTION_SIX}}" role="tabpanel">
<form [formGroup]="financialSectionSix">

<label class="form-check-label" for="financial1">
  <input required formControlName="medicaidOrSssi" id="medicaidOrSssi" 
    class="form-check-input"
    data-hint="yes" type="checkbox" value="true">
  Medicaid or Supplemental Security Income (SSI)
</label>


<label class="form-check-label" for="cada-form-student-financial- 
  section-6-1-2">
  <input required formControlName="snap" id="snap" class="form-check- 
    input" data-hint="yes" type="checkbox"
     value='true'>
  Food Stamps or Supplemental Nutrition Assistance Program (SNAP)
  </label>

<label class="form-check-label" for="cada-form-student-financial- 
 section-6-1-6">
  <input required formControlName="noneOfTheAbove" id="noneOfTheAbove" 
    class="form-check-input" data-hint="yes" type="checkbox" value='true' 
    id="cada-form-student-financial-section-6-1-6"> None of the Above
  </label>
 </form>
</div>

I need the last input field to ONLY uncheck all other checkboxes in this form group,

I also need to be able to keep my validation as well, using ngModel caused issues with that since my form controls were not able to be registered.

1条回答
Explosion°爆炸
2楼-- · 2019-07-24 03:13

You can keep the final checkbox as it's own control (not registered to the form group) and just listen to the change event on that checkbox: E.g:

<input required formControlName="noneOfTheAbove" id="noneOfTheAbove" 
class="form-check-input" data-hint="yes" type="checkbox" value='true' 
id="cada-form-student-financial-section-6-1-6" (change)="unselectAll()"> 
None of the Above

In your component.ts file:

unselectAll() {
   this.form.patchValue({
   medicaidOrSssi: false,
   snap: false,
   freeOrReducedPriceLunch: false, 
   tanf: false,
   wic: false
 });
}
查看更多
登录 后发表回答