【问题标题】:Angular2 How to get all selected check boxesAngular2如何获取所有选中的复选框
【发布时间】:2016-03-17 02:38:43
【问题描述】:

所以我正在开发一个 Angular2 应用程序。 我有一个表格,其中每条记录代表一个学生并包含一个复选框

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

在某些时候,用户会点击一个按钮,该按钮需要获取所有选中复选框的值。

我不确定我应该向谁提出这个问题。

一个想法是每个学生都有一个检查或不检查的值。这必须通过双向绑定来完成。

但是这意味着每次你必须通过所有的学生

这是最好的选择吗? 是否有与以下 JQuery 匹配的内容:

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

【问题讨论】:

  • ng-model呢,可以用这个吗?
  • 你能创建一个jsfiddle吗,jsfiddle.net
  • 根本不需要 jQuery
  • @Jai 如何使用 ng-model ?
  • @charlietfl 当然不应该。我的意思是我正在寻找类似的东西。

标签: jquery checkbox data-binding angular two-way


【解决方案1】:

我最近回答了一个类似的问题:https://stackoverflow.com/a/34142740/215945

您可以在模板中执行以下操作:

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

然后,对选定的学生做一些事情:

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

【讨论】:

  • 我认为现在应该是 [(ngModel)]。
【解决方案2】:

另一种方法是这样的:

.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>

在 .ts 文件中

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);
    }

【讨论】:

  • @pradeep,你节省了我很多时间。谢谢
【解决方案3】:

只需在按钮上添加一个条件,并记得检查复选框字段的“值”,如下所示:

<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>

【讨论】:

    【解决方案4】:

    您也可以使用“formbuilder”以与我的上一个类似的方式进行操作。发帖如下:

    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);
        }
    }
    

    【讨论】:

      【解决方案5】:

      PrimeNG DataTable 将此作为内置功能。只需将 selectionMode 设置为 multiple 即可获得基于复选框的选择。现场演示在http://www.primefaces.org/primeng/#/datatableselection

      【讨论】:

        【解决方案6】:
        1. 我刚刚为那些正在使用 价值对象。 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.创建一个列表——xyzlist。 3. 赋值,我在这个列表中传递来自 Java 的值。 4. 值是 Int-Id,经过布尔检查(可以在 Component.ts 中传递)。 5. 现在在 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);
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-10
          • 2023-03-10
          • 1970-01-01
          • 1970-01-01
          • 2015-06-28
          • 1970-01-01
          相关资源
          最近更新 更多