Angular 6 how to pass selected checkbox to ngModel

Issue

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?

Solution

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

Answered By – Sachila Ranawaka

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.