Angular2 How to get all selected check boxes

Abdelrahman Shoman picture Abdelrahman Shoman · Dec 11, 2015 · Viewed 21.7k times · Source

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(){

Answer

Mark Rajcok picture Mark Rajcok · Dec 11, 2015

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(_ => { ... })