Angular 6 how to pass selected checkbox to ngModel

emka26 picture emka26 · Sep 11, 2018 · Viewed 13.3k times · Source

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?

Answer

Sachila Ranawaka picture Sachila Ranawaka · Sep 11, 2018

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