Search code examples
jquerycheckboxdata-bindingangulartwo-way

Angular2 How to get all selected check boxes


So I am working on an Angular2 application. I have a table where each record represent a student and includes a checkbox

<input class="mycheckbox" type="checkbox" [value]='student.StudentId'>

At some point user will click on a button that needs to get the value of all selected check-boxes.

I am not sure who should I address this.

One idea is that each student will have a value of checked or not. And this has to be done through two-way bindings.

However this will imply that each time u have to go through all students

Is this the best available option ? And is there something that matches the following JQuery:

$('.mycheckbox:checked').each(function(){

Solution

  • I recently answered a similar question: https://stackoverflow.com/a/34142740/215945

    You could do the following in your template:

    <input class="mycheckbox" type="checkbox" [(ngModel)]="student.selected">{{student.StudendId}}
    

    Then, to do something with the selected students:

    this.students.filter(_ => _.selected).forEach(_ => { ... })