Angular 6 how to pass selected checkbox to ngModel

16,885

Solution 1

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

Solution 2

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 
  },  
]
Share:
16,885
emka26
Author by

emka26

Updated on June 09, 2022

Comments

  • emka26
    emka26 almost 2 years

    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?

  • MukulSharma
    MukulSharma over 5 years
    But how to find check uncheck from here?