cdslijngard
cdslijngard

Reputation: 196

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" /> {{type.value}}
            </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.

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

Upvotes: 2

Views: 1743

Answers (3)

memon asrar
memon asrar

Reputation: 1

In angular every model bind with name , means you need to give unique name to each Form elements`

For Example:

<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="type.id" [(ngModel)]="client.responseTypes[i].checked" /> {{type.value}}
        </label>
      </div>
    </div>
  </div>

Object :

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

And now Check :) Thank you

Upvotes: 0

cdslijngard
cdslijngard

Reputation: 196

Alright after trying to wrap my head around why my local application wasn't showing the result I wanted, I started to copy and paste my form-group out of the <form></form> element it was in.

Ta-daa, it works now.

FYI: Placing *ngFor checkboxes inside a <form></form> element results in unwanted behaviour.

Upvotes: 0

Eliseo
Eliseo

Reputation: 57939

the syntax is ok, well, you can do too

<input type="checkbox" name="responseTypes" [(ngModel)]="type.checked">

the problem is in other place (when you defined the client -I think you write some like this.client.responseTypes=...-), you can write

{{client |json }}

to check it

Upvotes: 0

Related Questions