vendredi 6 octobre 2017

Angular 2 - Handling multiple checkboxes checked state

I'm building a registration form, and have to handle multiple checkboxes generated through *ngFor structural directive.

Template:

<div class="form-group">
        <label class="col-lg-3 control-label">Response Type</label>
        <div class="col-lg-7">
          <div class="checkbox" *ngFor="let type of client.responseTypes; let i = index">
            <label>
              <input type="checkbox" name="responseTypes" [(ngModel)]="client.responseTypes[i].checked" /> 
            </label>
          </div>
        </div>
      </div>

TS model object:

client.responseTypes = [
{ value: 'type1', checked: false},
          { value: 'type2', checked: true },
          { value: 'type3', checked: true }
];

The actual values behind the scene checked or unchecked are stored correctly. But, the checkboxes do not show the correct value.

  • If one of the three objects.checked == false, all checkboxes will show unchecked
  • Only if all three objects.checked == true, all three will be checked in the form.

enter image description here

I tried fiddling with [value]="client.responseTypes[i].checked" and [checked]="client.responseTypes[i].checked" on the input element, but to no success.

Any pointers in the right direction are massively appreciated.

Regards, Chris




Aucun commentaire:

Enregistrer un commentaire