Angular 6 how to pass selected checkbox to ngModel
Asked Answered
G

2

6

I have problem with pass selected checkbox (which is iterated) to ngModel.

    <label class="btn btn-outline-secondary" 
     *ngFor="let test of tests"  >
      <input type="checkbox">
    </label>

in ts I have model:

     testData = <any>{};

this.tests = [{
    id: 1, name: 'test1' 
  },
  {
    id: 2, name: 'test2' 
  },
  {
    id: 3, name: 'test3' 
  },  
]

I tried with ngModel and ngModelChange, but still have problem with display selected checkbox. How can I do this?

Gregorygregrory answered 11/9, 2018 at 10:41 Comment(0)
A
9

use [(ngModel)]="test.name"

 <label class="btn btn-outline-secondary" *ngFor="let test of tests"  >
  <input type="checkbox" [(ngModel)]="test.selected" > {{test.name}} - {{test.selected}}
</label>

Demo

Appellation answered 11/9, 2018 at 10:43 Comment(1)
But how to find check uncheck from here?Heavily
C
6

I suggest you add a property in your model and bind it in the template.

<label class="btn btn-outline-secondary" *ngFor="let test of tests"  >
    <input type="checkbox" [(ngModel)]="test.isChecked">
</label>
this.tests = [{
    id: 1, name: 'test1', isChecked: false
  },
  {
    id: 2, name: 'test2', isChecked: true
  },
  {
    id: 3, name: 'test3', isChecked: false 
  },  
]
Chanda answered 11/9, 2018 at 11:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.