Angular 2:获取多个选中复选框的值
Angular 2: Get Values of Multiple Checked Checkboxes
我的问题很简单:我有一个这样的复选框列表:
<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>
我想发送一组选定的选项,例如:
[option1, option5, option8]
如果选择选项 1、5 和 8。该数组是我想通过 HTTP PUT 请求发送的 JSON 的一部分。
感谢您的帮助!
<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
}
}
感谢 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>
这是我正在使用的 3 个对象:
options = ['OptionA', 'OptionB', 'OptionC'];
optionsMap = {
OptionA: false,
OptionB: false,
OptionC: false,
};
optionsChecked = [];
还有3个有用的方法:
1。启动 optionsMap
:
initOptionsMap() {
for (var x = 0; x<this.order.options.length; x++) {
this.optionsMap[this.options[x]] = true;
}
}
2.更新optionsMap
:
updateCheckedOptions(option, event) {
this.optionsMap[option] = event.target.checked;
}
3. 将 optionsMap
转换为 optionsChecked
并在发送 POST 请求之前将其存储在 options
中:
updateOptions() {
for(var x in this.optionsMap) {
if(this.optionsMap[x]) {
this.optionsChecked.push(x);
}
}
this.options = this.optionsChecked;
this.optionsChecked = [];
}
这是使用 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)
}
}
我只是为那些使用列表的人简化了一点
值对象。
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**.
创建列表 -- xyzlist.
- 赋值,我正在传递此列表中 Java 的值。
- 值为 Int-Id,布尔值检查(可以传入 Component.ts)。
现在获取 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);
}
我遇到了同样的问题,现在我有一个更喜欢的答案(也许你也是)。我已将每个复选框绑定到一个数组索引。
首先我定义了一个这样的对象:
SelectionStatusOfMutants: any = {};
然后复选框是这样的:
<input *ngFor="let Mutant of Mutants" type="checkbox"
[(ngModel)]="SelectionStatusOfMutants[Mutant.Id]" [value]="Mutant.Id" />
如你所知,JS 中的对象是具有任意索引的数组。所以获取结果如此简单:
像这样计算选定的:
let count = 0;
Object.keys(SelectionStatusOfMutants).forEach((item, index) => {
if (SelectionStatusOfMutants[item])
count++;
});
类似于这样获取选定的:
let selecteds = Object.keys(SelectionStatusOfMutants).filter((item, index) => {
return SelectionStatusOfMutants[item];
});
看到了吗?!很简单很漂亮。 TG.
希望对遇到同样问题的人有所帮助。
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
flightids 数组将有另一个像这样的数组
[ [真,'id_1'],[假,'id_2'],[真,'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);
}
我刚遇到这个问题,并决定尽可能减少所有变量,以保持工作区清洁。这是我的代码示例
<input type="checkbox" (change)="changeModel($event, modelArr, option.value)" [checked]="modelArr.includes(option.value)" />
调用更改的方法是在模型中推送值,或删除它。
public changeModel(ev, list, val) {
if (ev.target.checked) {
list.push(val);
} else {
let i = list.indexOf(val);
list.splice(i, 1);
}
}
创建一个列表,如:-
this.xyzlist = [
{
id: 1,
value: 'option1'
},
{
id: 2,
value: 'option2'
}
];
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>
然后在它的组件 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);
}
@ccwasden 上面的解决方案对我来说只是一个小改动,每个复选框都必须有一个唯一的名称,否则绑定将不起作用
<div class="form-group">
<label for="options">Options:</label>
<div *ngFor="let option of options; let i = index">
<label>
<input type="checkbox"
name="options_{{i}}"
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)
}
}
并确保在您的主模块中导入 FormsModule
import { FormsModule } from '@angular/forms';
imports: [
FormsModule
],
由于我花了很长时间解决了类似的问题,所以我回答以分享我的经验。
我的问题是一样的,要知道,在触发指定事件后获得许多复选框值。
我尝试了很多解决方案,但对我来说最性感的是使用 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());
}
在此处找到:
ref 的潜在其他解决方案,有很多类似的主题,none 其中的目的是这个解决方案...:
- https://medium.com/@vladguleaev/reusable-angular-create-multiple-checkbox-group-component-84f0e4727677
- https://netbasal.com/handling-multiple-checkboxes-in-angular-forms-57eb8e846d21
- https://medium.com/@shlomiassaf/the-angular-template-variable-you-are-missing-return-of-the-var-6b573ec9fdc
- https://www.bennadel.com/blog/3205-using-form-controls-without-formsmodule-or-ngmodel-in-angular-2-4-1.htm
- Filter by checkbox in angular 5
这是一个没有地图、'checked' 属性和 FormControl 的解决方案。
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:
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)
}
}
In Angular 2+ 到 9 使用 Typescript
来源Link
我们可以用一个对象绑定多个Checkbox
checkboxesDataList = [
{
id: 'C001',
label: 'Photography',
isChecked: true
},
{
id: 'C002',
label: 'Writing',
isChecked: true
},
{
id: 'C003',
label: 'Painting',
isChecked: true
},
{
id: 'C004',
label: 'Knitting',
isChecked: false
},
{
id: 'C004',
label: 'Dancing',
isChecked: false
},
{
id: 'C005',
label: 'Gardening',
isChecked: true
},
{
id: 'C006',
label: 'Drawing',
isChecked: true
},
{
id: 'C007',
label: 'Gyming',
isChecked: false
},
{
id: 'C008',
label: 'Cooking',
isChecked: true
},
{
id: 'C009',
label: 'Scrapbooking',
isChecked: false
},
{
id: 'C010',
label: 'Origami',
isChecked: false
}
]
在HTML模板中使用
<ul class="checkbox-items">
<li *ngFor="let item of checkboxesDataList">
<input type="checkbox" [(ngModel)]="item.isChecked" (change)="changeSelection()">{{item.label}}
</li>
</ul>
要获取选中的复选框,请在class
中添加以下方法
// Selected item
fetchSelectedItems() {
this.selectedItemsList = this.checkboxesDataList.filter((value, index) => {
return value.isChecked
});
}
// IDs of selected item
fetchCheckedIDs() {
this.checkedIDs = []
this.checkboxesDataList.forEach((value, index) => {
if (value.isChecked) {
this.checkedIDs.push(value.id);
}
});
}
我的问题很简单:我有一个这样的复选框列表:
<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>
我想发送一组选定的选项,例如:
[option1, option5, option8]
如果选择选项 1、5 和 8。该数组是我想通过 HTTP PUT 请求发送的 JSON 的一部分。
感谢您的帮助!
<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
}
}
感谢 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>
这是我正在使用的 3 个对象:
options = ['OptionA', 'OptionB', 'OptionC'];
optionsMap = {
OptionA: false,
OptionB: false,
OptionC: false,
};
optionsChecked = [];
还有3个有用的方法:
1。启动 optionsMap
:
initOptionsMap() {
for (var x = 0; x<this.order.options.length; x++) {
this.optionsMap[this.options[x]] = true;
}
}
2.更新optionsMap
:
updateCheckedOptions(option, event) {
this.optionsMap[option] = event.target.checked;
}
3. 将 optionsMap
转换为 optionsChecked
并在发送 POST 请求之前将其存储在 options
中:
updateOptions() {
for(var x in this.optionsMap) {
if(this.optionsMap[x]) {
this.optionsChecked.push(x);
}
}
this.options = this.optionsChecked;
this.optionsChecked = [];
}
这是使用 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)
}
}
我只是为那些使用列表的人简化了一点 值对象。 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**.
创建列表 -- xyzlist.
- 赋值,我正在传递此列表中 Java 的值。
- 值为 Int-Id,布尔值检查(可以传入 Component.ts)。
现在获取 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); }
我遇到了同样的问题,现在我有一个更喜欢的答案(也许你也是)。我已将每个复选框绑定到一个数组索引。
首先我定义了一个这样的对象:
SelectionStatusOfMutants: any = {};
然后复选框是这样的:
<input *ngFor="let Mutant of Mutants" type="checkbox"
[(ngModel)]="SelectionStatusOfMutants[Mutant.Id]" [value]="Mutant.Id" />
如你所知,JS 中的对象是具有任意索引的数组。所以获取结果如此简单:
像这样计算选定的:
let count = 0;
Object.keys(SelectionStatusOfMutants).forEach((item, index) => {
if (SelectionStatusOfMutants[item])
count++;
});
类似于这样获取选定的:
let selecteds = Object.keys(SelectionStatusOfMutants).filter((item, index) => {
return SelectionStatusOfMutants[item];
});
看到了吗?!很简单很漂亮。 TG.
希望对遇到同样问题的人有所帮助。
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
flightids 数组将有另一个像这样的数组 [ [真,'id_1'],[假,'id_2'],[真,'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);
}
我刚遇到这个问题,并决定尽可能减少所有变量,以保持工作区清洁。这是我的代码示例
<input type="checkbox" (change)="changeModel($event, modelArr, option.value)" [checked]="modelArr.includes(option.value)" />
调用更改的方法是在模型中推送值,或删除它。
public changeModel(ev, list, val) {
if (ev.target.checked) {
list.push(val);
} else {
let i = list.indexOf(val);
list.splice(i, 1);
}
}
创建一个列表,如:-
this.xyzlist = [
{
id: 1,
value: 'option1'
},
{
id: 2,
value: 'option2'
}
];
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>
然后在它的组件 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);
}
@ccwasden 上面的解决方案对我来说只是一个小改动,每个复选框都必须有一个唯一的名称,否则绑定将不起作用
<div class="form-group">
<label for="options">Options:</label>
<div *ngFor="let option of options; let i = index">
<label>
<input type="checkbox"
name="options_{{i}}"
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)
}
}
并确保在您的主模块中导入 FormsModule
import { FormsModule } from '@angular/forms';
imports: [
FormsModule
],
由于我花了很长时间解决了类似的问题,所以我回答以分享我的经验。 我的问题是一样的,要知道,在触发指定事件后获得许多复选框值。 我尝试了很多解决方案,但对我来说最性感的是使用 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());
}
在此处找到:
ref 的潜在其他解决方案,有很多类似的主题,none 其中的目的是这个解决方案...:
- https://medium.com/@vladguleaev/reusable-angular-create-multiple-checkbox-group-component-84f0e4727677
- https://netbasal.com/handling-multiple-checkboxes-in-angular-forms-57eb8e846d21
- https://medium.com/@shlomiassaf/the-angular-template-variable-you-are-missing-return-of-the-var-6b573ec9fdc
- https://www.bennadel.com/blog/3205-using-form-controls-without-formsmodule-or-ngmodel-in-angular-2-4-1.htm
- Filter by checkbox in angular 5
这是一个没有地图、'checked' 属性和 FormControl 的解决方案。
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:
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)
}
}
In Angular 2+ 到 9 使用 Typescript
来源Link
我们可以用一个对象绑定多个Checkbox
checkboxesDataList = [
{
id: 'C001',
label: 'Photography',
isChecked: true
},
{
id: 'C002',
label: 'Writing',
isChecked: true
},
{
id: 'C003',
label: 'Painting',
isChecked: true
},
{
id: 'C004',
label: 'Knitting',
isChecked: false
},
{
id: 'C004',
label: 'Dancing',
isChecked: false
},
{
id: 'C005',
label: 'Gardening',
isChecked: true
},
{
id: 'C006',
label: 'Drawing',
isChecked: true
},
{
id: 'C007',
label: 'Gyming',
isChecked: false
},
{
id: 'C008',
label: 'Cooking',
isChecked: true
},
{
id: 'C009',
label: 'Scrapbooking',
isChecked: false
},
{
id: 'C010',
label: 'Origami',
isChecked: false
}
]
在HTML模板中使用
<ul class="checkbox-items">
<li *ngFor="let item of checkboxesDataList">
<input type="checkbox" [(ngModel)]="item.isChecked" (change)="changeSelection()">{{item.label}}
</li>
</ul>
要获取选中的复选框,请在class
中添加以下方法 // Selected item
fetchSelectedItems() {
this.selectedItemsList = this.checkboxesDataList.filter((value, index) => {
return value.isChecked
});
}
// IDs of selected item
fetchCheckedIDs() {
this.checkedIDs = []
this.checkboxesDataList.forEach((value, index) => {
if (value.isChecked) {
this.checkedIDs.push(value.id);
}
});
}