角2:获取多个复选框的值

时间:2021-10-20 09:47:52

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!

谢谢你的帮助!

8 个解决方案

#1


74  

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

这里有一个使用ngModel(最终角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)
  }
}

#2


23  

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

多亏了冈特,我找到了解决办法!这是我的全部代码,如果它可以帮助任何人:

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

有三种有用的方法:

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 optionsMap into optionsChecked and store it in options before sending the POST request:

3所示。将optionsMap转换为optionsChecked,并将其存储在选项中,然后发送POST请求:

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

#3


5  

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

}

}

#4


3  

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

#5


2  

  1. I have just simplified little bit for those whose are using list of value Object. XYZ.Comonent.html

    对于那些使用value对象列表的人,我简化了一点。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**.

    * * XYZ.Component.ts * *。

  2. create a list -- xyzlist.

    创建一个列表——xyzlist。

  3. assign values, I am passing values from Java in this list.
  4. 赋值,我正在从这个列表中传递Java的值。
  5. Values are Int-Id, boolean -checked (Can Pass in Component.ts).
  6. 值是Int-Id、boolean -checked(可以传入Component.ts)。
  7. Now to get value in Componenet.ts.

    现在来获取component .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);
    
        }
    

#6


1  

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:

类似于这样的选择:

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

You see?! Very simple very beautiful. TG.

你看到了什么? !很简单很漂亮。TG。

#7


1  

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

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

templet.html

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

component.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);

}

#8


1  

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.

方法(调用change)是在模型中推值或删除值。

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

#1


74  

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

这里有一个使用ngModel(最终角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)
  }
}

#2


23  

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

多亏了冈特,我找到了解决办法!这是我的全部代码,如果它可以帮助任何人:

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

有三种有用的方法:

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 optionsMap into optionsChecked and store it in options before sending the POST request:

3所示。将optionsMap转换为optionsChecked,并将其存储在选项中,然后发送POST请求:

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

#3


5  

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

}

}

#4


3  

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

#5


2  

  1. I have just simplified little bit for those whose are using list of value Object. XYZ.Comonent.html

    对于那些使用value对象列表的人,我简化了一点。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**.

    * * XYZ.Component.ts * *。

  2. create a list -- xyzlist.

    创建一个列表——xyzlist。

  3. assign values, I am passing values from Java in this list.
  4. 赋值,我正在从这个列表中传递Java的值。
  5. Values are Int-Id, boolean -checked (Can Pass in Component.ts).
  6. 值是Int-Id、boolean -checked(可以传入Component.ts)。
  7. Now to get value in Componenet.ts.

    现在来获取component .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);
    
        }
    

#6


1  

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:

类似于这样的选择:

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

You see?! Very simple very beautiful. TG.

你看到了什么? !很简单很漂亮。TG。

#7


1  

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

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

templet.html

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

component.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);

}

#8


1  

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.

方法(调用change)是在模型中推值或删除值。

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