从所有选中的复选框中获取价值 [英] Get value from all checked checkbox in angular
问题描述
我正在使用angular创建测验应用,而我有这样的代码
i'm creating quiz app using angular and i have code like this
ngOnInit() {
this.myForm = this.fb.group({
lessonCode: "test",
answer: this.fb.array([])
});
}
onChange(email: string, code: string, isChecked: boolean) {
const emailFormArray = <FormArray>this.myForm.controls.answer;
if (isChecked) {
let array = new FormGroup({
questionCode: new FormControl(email),
emailCode: new FormArray([
new FormControl(code)
]),
});
emailFormArray.push(array);
} else {
let index = emailFormArray.controls.findIndex(x => x.value == email);
emailFormArray.removeAt(index);
}
}
这样产生数组
Form values: {
"lessonCode": "test",
"answer": [
{
"questionCode": "pertanyaan2",
"emailCode": [
"option2"
]
},
{
"questionCode": "pertanyaan2",
"emailCode": [
"option1"
]
}
]
}
但是我实际需要的是这样的
but what i'm actually needed is like this
Form values: {
"lessonCode": "test",
"answer": [
{
"questionCode": "pertanyaan2",
"emailCode": {
"option2",
"option1"
}
}
]
}
我该如何实现?任何想法都会很有帮助
how can i achieve that? any thoughts would be very helpful
我在此处的复制量很小 https://stackblitz.com/edit/angular-ca1jin?file=src%2Fapp%2Fapp.component.ts
i have minimal reproduce here https://stackblitz.com/edit/angular-ca1jin?file=src%2Fapp%2Fapp.component.ts
推荐答案
您需要做的是将emailCode
添加为FormArray
而不是FormControl
,这样您就可以检查emailCode
.
What you need to do is to add emailCode
as FormArray
instead of FormControl
, this way you will be able to check whether the questionCode
already exists, and if yes, you can append to emailCode
the option you checked.
唯一需要更改的是您的onChange
方法
The only things to change are on your onChange
method
首先是array
变量,您需要添加FormArray
而不是FormControl
First you array
variable, you need to add FormArray
instead of FormControl
let array = new FormGroup({
questionCode: new FormControl(email),
emailCode: new FormArray([])
});
然后为您的选中选项创建FormControl
Then create a FormControl
for your checked option
let codeOption = new FormControl(code)
最后,在您的if
条件下,检查是否存在questionCode可以将formControl附加到它上面,或者创建一个新对象.
And finally, in your if
condition, check if the questionCode already exist to just append your formControl to it, or to create a new object.
if (isChecked) {
if (emailFormArray.controls.some(obj => obj.get('questionCode').value == email)){
(<FormArray>emailFormArray.controls.find(obj => obj.get('questionCode').value == email).get('emailCode')).push(codeOption);
}else{
(<FormArray>array.get('emailCode')).push(codeOption)
emailFormArray.push(array)
}
}
更清楚地说,我已经修改了您的 stackblitz 满足您的需求
To be more clear I have modified your stackblitz to fit with your needs
我还没有修改else
条件来删除FormArray
上的选项,但是您只需要复制if
条件就可以得到code
元素在emailCode
上的索引. >.
I have not modified the else
condition to remove the options on your FormArray
but you just need to copy the if
condition to get the index of the code
element on your FormArray
of emailCode
.
这篇关于从所有选中的复选框中获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!