Angular2 How to get all selected check boxes
Asked Answered
P

6

7

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(){
Proselytize answered 11/12, 2015 at 8:37 Comment(6)
what about ng-model, you can use this?Liebfraumilch
could you create a jsfiddle,jsfiddle.netMustachio
shouldn't need jQuery at all for thisVibrant
@Liebfraumilch How can I use ng-model ?Proselytize
@Vibrant Of course I shouldn't. I meant that I am looking for something similar.Proselytize
If you use ngFor over an array of students you can bind to the array items and then just filter the studends where the value is true.Bluecollar
D
8

I recently answered a similar question: https://mcmap.net/q/556496/-angular2-disable-button-if-no-checkbox-selected

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(_ => { ... })
Diluvium answered 11/12, 2015 at 20:44 Comment(1)
I believe it should be [(ngModel)] now.Flagwaving
P
2

Another way to do the same is like this:

.html

<button value="all" (click)="bulk('all')">ALL</button>
<button value="none" (click)="bulk('none')">NONE</button>

<div *ngFor="#students of student_list #i=index">
  <input type="checkbox" value={{students.id}} class="checkedStudent"   
  (change)="checkedStudents(students.id)" id={{students.id}}>
</div>

in .ts file

abc:Array<any>= [];
checkedStudents(value) {
        console.log(value);
        if ((<HTMLInputElement>document.getElementById(value)).checked === true) {
            this.abc.push(value);
        }
        else if ((<HTMLInputElement>document.getElementById(value)).checked === false) {
            let indexx = this.abc.indexOf(value);
            this.abc.splice(indexx,1)
        }
        console.log(this.abc)
    }

// for Bulk actions

bulk(a) {
        // console.log(a);
        if (a == "all") {
            console.log("yes all");
            this.abc = [];
            for (let i = 0; i < this.student_list.length; i++) {
                (<HTMLInputElement>document.getElementsByClassName("checkedStudent")[i]).checked = true;
                this.abc.push(this.student_list[i].id);
            }
        }
        if (a == "none") {
            for (let i = 0; i < this.student_list.length; i++) {
                (<HTMLInputElement>document.getElementsByClassName("checkedStudent")[i]).checked = false;
            }
            this.abc = [];
        }
        console.log(this.abc);
    }
Putt answered 4/2, 2016 at 19:16 Comment(1)
@pradeep, you saved my lot of time. ThanksHoover
J
1

Simply add a conditional to the button and remember to check the 'value' of the checkbox field as follows:

<form 
    #f="ngForm"  
    (ngSubmit)="onSubmit(f.value)" >

    <div class="form-group">

        <h2>Enter Email for Newsletter :</h2> <br/>

        <input 

            #registrationemail="ngForm"
            ngControl="registrationemail" 

            placeholder="Email Address"
            required type="email" 
            class="form-control" 
            pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"  />

        <div *ngIf="registrationemail.touched && registrationemail.errors" class="alert alert-danger">
            <div  *ngIf="registrationemail.errors.required" >An Email is required</div>
            <div  *ngIf="registrationemail.errors.pattern">Email is invalid</div>
        </div>

    </div>

    <div class="form-group">


        <input 
        id="accepttermsconditions"
        #accepttermsconditions="ngForm"
         ngControl="accepttermsconditions" 
        type="checkbox" 
        checked/>
        <label for="accepttermsconditions">Accept Terms and Conditions </label> 
        </div>

    <button
       [disabled]="!f.valid || 
        !accepttermsconditions.value"
      class="btn btn-primary" 
      type="submit">Submit </button>

</form>
Jiva answered 28/5, 2016 at 15:37 Comment(0)
J
0

You can also do it using 'formbuilder' in a simialr way to my prev. post as follows:

import {Component, OnInit} from '@angular/core';
import { FORM_DIRECTIVES, FormBuilder, ControlGroup } from '@angular/common';

@Component({
    selector: 'registration-form',
    directives: [FORM_DIRECTIVES],
    template: `

    <form 
    [ngFormModel]="myForm" 
        (ngSubmit)="onSubmit(myForm.value)" 
        class="ui form"> 

          <div class="form-group">
     <label for="registrationemailInput">EMail Address</label>  
     <input type="email"  
            required
            id="registrationemailInput" 
            placeholder="email address"  
            [ngFormControl]="myForm.controls['registrationemail']"
            class="form-control" 
            pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"
             />


                <div *ngIf="myForm.controls['registrationemail'].touched && myForm.controls['registrationemail'].errors" class="alert alert-danger">
            <div  *ngIf="myForm.controls['registrationemail'].errors.required" >An Email is required</div>
            <div  *ngIf="myForm.controls['registrationemail'].errors.pattern">Email is invalid</div>
        </div>

            </div>

            <div class="form-group">
            <label for="termsandconditions">Accept Terms &amp; Conditions</label>
      <input  id="termsandconditions"
                type="checkbox"
                checked      
                [ngFormControl]="myForm.controls['accepttermsconditions']" 
                id="accepttermsconditions"
      />
      </div>

      <button 

       [disabled]="!myForm.valid || !myForm.controls['accepttermsconditions'].value"

            class="btn btn-primary"  
            type="submit">Submit</button>
     </form>`
})
export class FormbuilderComponent implements OnInit {

    myForm: ControlGroup;

    constructor(fb: FormBuilder) {
        this.myForm = fb.group({
            'registrationemail': ['test'],
            'accepttermsconditions': [true]
        })
    }

    ngOnInit() {
    }


    onSubmit(form: any): void {
        console.log('you submitted value:', form);
    }
}
Jiva answered 28/5, 2016 at 16:26 Comment(0)
B
0

PrimeNG DataTable has this as a built-in feature. Simply set selectionMode to multiple to get check box based selection. Live demo is at http://www.primefaces.org/primeng/#/datatableselection

Bag answered 26/7, 2016 at 18:36 Comment(0)
L
0
  1. I have just simplified little bit for those whose are using list of value Object. XYZ.Comonent.html.

<div class="form-group">
        <label for="options">Options :</label>
        <div *ngFor="let option of xyzlist">
            <label>
                <input type="checkbox"
                       name="options"
                       value="{{option.Id}}"

                       (change)="onClicked(option, $event)"/>
                {{option.Id}}-- {{option.checked}}
            </label>
        </div>
        <button type="submit">Submit</button>
    </div> 

** XYZ.Component.ts**. 2. create a list -- xyzlist. 3. assign values, I am passing values from Java in this list. 4. Values are Int-Id, boolean -checked (Can Pass in Component.ts). 5. Now to get value in Componenet.ts.

    onClicked(option, event) {
console.log("event  " + this.xyzlist.length);
console.log("event  checked" + event.target.checked);
console.log("event  checked" + event.target.value);
for (var i = 0; i < this.xyzlist.length; i++) {
    console.log("test --- " + this.xyzlist[i].Id;
    if (this.xyzlist[i].Id == event.target.value) {
        this.xyzlist[i].checked = event.target.checked;
    }
    console.log("after update of checkbox" + this.xyzlist[i].checked);

}
Laspisa answered 19/12, 2016 at 6:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.