json Angular 2:获取多个选中复选框的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34997128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:15:24  来源:igfitidea点击:

Angular 2: Get Values of Multiple Checked Checkboxes

jsonformscheckboxangularangular2-forms

提问by Yannick Morel

My problem is really simple: I have a list of checkboxes like this:

我的问题很简单:我有一个这样的复选框列表:

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

And I would like to send an array of the selected options, something like: [option1, option5, option8]if options 1, 5 and 8 are selected. This array is part of a JSON that I would like to send via an HTTP PUT request.

我想发送一组选定的选项,例如: [option1, option5, option8]如果选择了选项 1、5 和 8。这个数组是我想通过 HTTP PUT 请求发送的 JSON 的一部分。

Thanks for your help!

谢谢你的帮助!

采纳答案by Yannick Morel

I have find a solution thanks to Gunter! Here is my whole code if it could help anyone:

感谢 Gunter,我找到了解决方案!如果它可以帮助任何人,这是我的整个代码:

<div class="form-group">
            <label for="options">Options :</label>
            <div *ngFor="#option of options; #i = index">
                <label>
                    <input type="checkbox"
                           name="options"
                           value="{{option}}"
                           [checked]="options.indexOf(option) >= 0"
                           (change)="updateCheckedOptions(option, $event)"/>
                    {{option}}
                </label>
            </div>
        </div>

Here are the 3 objects I'm using:

这是我正在使用的 3 个对象:

options = ['OptionA', 'OptionB', 'OptionC'];
optionsMap = {
        OptionA: false,
        OptionB: false,
        OptionC: false,
};
optionsChecked = [];

And there are 3 useful methods:

还有3个有用的方法:

1. To initiate optionsMap:

1. 启动optionsMap

initOptionsMap() {
    for (var x = 0; x<this.order.options.length; x++) {
        this.optionsMap[this.options[x]] = true;
    }
}

2.to update the optionsMap:

2.更新optionsMap

updateCheckedOptions(option, event) {
   this.optionsMap[option] = event.target.checked;
}

3.to convert optionsMapinto optionsCheckedand store it in optionsbefore sending the POST request:

3.转换optionsMapoptionsChecked并将其存储在options发送POST请求之前:

updateOptions() {
    for(var x in this.optionsMap) {
        if(this.optionsMap[x]) {
            this.optionsChecked.push(x);
        }
    }
    this.options = this.optionsChecked;
    this.optionsChecked = [];
}

回答by ccwasden

Here's a simple way using ngModel(final Angular 2)

这是使用ngModel(最终 Angular 2)的简单方法

<!-- my.component.html -->

<div class="form-group">
    <label for="options">Options:</label>
    <div *ngFor="let option of options">
        <label>
            <input type="checkbox"
                   name="options"
                   value="{{option.value}}"
                   [(ngModel)]="option.checked"/>
            {{option.name}}
        </label>
    </div>
</div>


// my.component.ts

@Component({ moduleId:module.id, templateUrl:'my.component.html'})

export class MyComponent {
  options = [
    {name:'OptionA', value:'1', checked:true},
    {name:'OptionB', value:'2', checked:false},
    {name:'OptionC', value:'3', checked:true}
  ]

  get selectedOptions() { // right now: ['1','3']
    return this.options
              .filter(opt => opt.checked)
              .map(opt => opt.value)
  }
}

回答by Alok Kamboj

create a list like :-

创建一个列表,如:-

this.xyzlist = [
  {
    id: 1,
    value: 'option1'
  },
  {
    id: 2,
    value: 'option2'
  }
];

Html :-

html :-

<div class="checkbox" *ngFor="let list of xyzlist">
            <label>
              <input formControlName="interestSectors" type="checkbox" value="{{list.id}}" (change)="onCheckboxChange(list,$event)">{{list.value}}</label>
          </div>

then in it's component ts :-

然后在它的组件 ts 中:-

onCheckboxChange(option, event) {
     if(event.target.checked) {
       this.checkedList.push(option.id);
     } else {
     for(var i=0 ; i < this.xyzlist.length; i++) {
       if(this.checkedList[i] == option.id) {
         this.checkedList.splice(i,1);
      }
    }
  }
  console.log(this.checkedList);
}

回答by Günter Z?chbauer

<input type="checkbox" name="options" value="option" (change)="updateChecked(option, $event)" /> 

export class MyComponent {
  checked: boolean[] = [];
  updateChecked(option, event) {
    this.checked[option]=event; // or `event.target.value` not sure what this event looks like
  }
}

回答by ConductedClever

I have encountered the same problem and now I have an answer I like more (may be you too). I have bounded each checkbox to an array index.

我遇到了同样的问题,现在我有了一个我更喜欢的答案(可能你也是)。我已将每个复选框绑定到一个数组索引。

First I defined an Object like this:

首先我定义了一个这样的对象:

SelectionStatusOfMutants: any = {};

Then the checkboxes are like this:

然后复选框是这样的:

<input *ngFor="let Mutant of Mutants" type="checkbox"
[(ngModel)]="SelectionStatusOfMutants[Mutant.Id]" [value]="Mutant.Id" />

As you know objects in JS are arrays with arbitrary indices. So the result are being fetched so simple:

如您所知,JS 中的对象是具有任意索引的数组。所以结果被获取如此简单:

Count selected ones like this:

像这样计算选定的:

let count = 0;
    Object.keys(SelectionStatusOfMutants).forEach((item, index) => {
        if (SelectionStatusOfMutants[item])
            count++;
    });

And similar to that fetch selected ones like this:

与 fetch 选择的类似,如下所示:

let selecteds = Object.keys(SelectionStatusOfMutants).filter((item, index) => {
        return SelectionStatusOfMutants[item];
    });

You see?! Very simple very beautiful. TG.

你看?!很简单很漂亮。TG。

回答by James Sung

I hope this would help someone who has the same problem.

我希望这会帮助有同样问题的人。

templet.html

模板.html

<form [formGroup] = "myForm" (ngSubmit) = "confirmFlights(myForm.value)">
  <ng-template ngFor [ngForOf]="flightList" let-flight let-i="index" >
     <input type="checkbox" [value]="flight.id" formControlName="flightid"
         (change)="flightids[i]=[$event.target.checked,$event.target.getAttribute('value')]" >
  </ng-template>
</form>

component.ts

组件.ts

flightids array will have another arrays like this [ [ true, 'id_1'], [ false, 'id_2'], [ true, 'id_3']...] here true means user checked it, false means user checked then unchecked it. The items that user have never checked will not be inserted to the array.

flightids 数组将有另一个这样的数组 [ [ true, 'id_1'], [ false, 'id_2'], [ true, 'id_3']...] 这里 true 表示用户检查它,false 表示用户检查然后取消选中它. 用户从未检查过的项目将不会插入到数组中。

flightids = []; 
confirmFlights(value){  
    //console.log(this.flightids);

    let confirmList = [];
    this.flightids.forEach(id => {
      if(id[0]) // here, true means that user checked the item 
        confirmList.push(this.flightList.find(x => x.id === id[1]));
    });
    //console.log(confirmList);

}

回答by tv1st

I just faced this issue, and decided to make everything work with as less variables as i can, to keep workspace clean. Here is example of my code

我刚刚遇到了这个问题,并决定使用尽可能少的变量使一切正常工作,以保持工作区干净。这是我的代码示例

<input type="checkbox" (change)="changeModel($event, modelArr, option.value)" [checked]="modelArr.includes(option.value)" />

Method, which called on change is pushing value in model, or removing it.

调用更改的方法是在模型中推送值或删除它。

public changeModel(ev, list, val) {
  if (ev.target.checked) {
    list.push(val);
  } else {
    let i = list.indexOf(val);
    list.splice(i, 1);
  }
}

回答by Gourav Bhatia

  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.

    xyzlist;//Just created a list
    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);
    
        }
    
  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, boolean -checked(可以传入 Component.ts)。
  5. 现在在 Componenet.ts 中获取价值。

    xyzlist;//Just created a list
    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);
    
        }
    

回答by 4x10m

Since I spent a long time solving a similar problem, I'm answering to share my experience. My problem was the same, to know, getting many checkboxes value after a specified event has been triggered. I tried a lot of solutions but for me the sexiest is using ViewChildren.

由于我花了很长时间解决类似的问题,所以我回答分享我的经验。我的问题是一样的,要知道,在触发指定事件后获得许多复选框值。我尝试了很多解决方案,但对我来说最性感的是使用ViewChildren

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components: QueryList<any>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}

Found here: https://stackoverflow.com/a/40165639/4775727

在这里找到:https: //stackoverflow.com/a/40165639/4775727

Potential other solutions for ref, there are a lot of similar topic, none of them purpose this solution...:

ref 的其他潜在解决方案,有很多类似的主题,但没有一个旨在解决此问题...:

回答by Dawnb

Here's a solution without map, 'checked' properties and FormControl.

这是一个没有地图、“已检查”属性和 FormControl 的解决方案。

app.component.html:

app.component.html:

<div *ngFor="let item of options">
  <input type="checkbox" 
  (change)="onChange($event.target.checked, item)"
  [checked]="checked(item)"
>
  {{item}}
</div>

app.component.ts:

app.component.ts:

  options = ["1", "2", "3", "4", "5"]
  selected = ["1", "2", "5"]

  // check if the item are selected
  checked(item){
    if(this.selected.indexOf(item) != -1){
      return true;
    }
  }

  // when checkbox change, add/remove the item from the array
  onChange(checked, item){
    if(checked){
    this.selected.push(item);
    } else {
      this.selected.splice(this.selected.indexOf(item), 1)
    }
  }

DEMO

演示