Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 how to pass selected checkbox to ngModel

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?

like image 270
emka26 Avatar asked Sep 11 '18 10:09

emka26


People also ask

How does angular handle multiple checkboxes?

The MultiSelect has built-in support to select multiple values through checkbox, when mode property set as CheckBox . To use checkbox, inject the CheckBoxSelection module in the MultiSelect.

Can't bind to ngModel since it isn't a known property of input Ng?

To fix Can't bind to 'ngModel' since it isn't a known property of 'input' error in Angular applications we have to import FormModule in app. module. ts file. If you are using FormBuilder class to create reactive form we have to import ReactiveFormsModule as well to avoid below error.

What does ng checked do?

Definition and Usage. The ng-checked directive sets the checked attribute of a checkbox or a radiobutton. The checkbox, or radiobutton, will be checked if the expression inside the ng-checked attribute returns true. The ng-checked directive is necessary to be able to shift the value between true and false .

How do you check checkbox is checked or not in angular 8?

Just define an ng-model directive in the checkbox and to find checkbox checked or not check model return value (TRUE or FALSE). If it has TRUE means checkbox is been checked.


2 Answers

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

like image 50
Sachila Ranawaka Avatar answered Sep 28 '22 08:09

Sachila Ranawaka


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 
  },  
]
like image 25
Stanisalv Dontsov Avatar answered Sep 28 '22 08:09

Stanisalv Dontsov