marcineck
marcineck

Reputation: 281

Angular 2 Reactive Form with checkboxes

Recently I've been trying to figure out how those Reactive Forms works. Basic examples (no nesting etc.) are understandable however if I have a form structure like this with checkboxes:

  {
  "username": "",
  "damnIt": "",
  "checkboxes": [
    {
      "checked": false,
      "name": "Checked1",
      "value": 10
    },
    {
      "checked": false,
      "name": "Checked1",
      "value": 11
    },
    {
      "checked": false,
      "name": "Checked1",
      "value": 12
    }
  ]
}

How should I render it on the template in order to change the "*checked" value (true | false)?

Upvotes: 1

Views: 729

Answers (1)

AngularChef
AngularChef

Reputation: 14087

You could do something like this:

  <form #theForm="ngForm" (ngSubmit)="submitForm(theForm.value)">

      <div *ngFor="let cb of data.checkboxes">
        <label>
          <input type="checkbox" [name]="cb.name" [(ngModel)]="cb.checked">{{cb.value}}
        </label>
      </div>

    <button type="submit" class="btn btn-primary">Submit</button>
  </form>

  <pre>{{data.checkboxes|json}}</pre>

See Plunkr: https://plnkr.co/edit/MpSO21fIJq1DtJoXmE3V?p=preview

Upvotes: 1

Related Questions