Javascript 如何使用Angular将复选框列表绑定到表单中?
我有一个表单,其中包含供用户检查的复选框列表,当用户提交表单时,它应该将复选框列表作为对象数组提交。相反,我什么也得不到 我在控制台中得到的是:Javascript 如何使用Angular将复选框列表绑定到表单中?,javascript,angular,typescript,Javascript,Angular,Typescript,我有一个表单,其中包含供用户检查的复选框列表,当用户提交表单时,它应该将复选框列表作为对象数组提交。相反,我什么也得不到 我在控制台中得到的是: {fruits:Array[0]} 我所期望的是: {fruits:Array[1]}//数组的数量取决于选中的复选框 下面是一个示例除了表单初始化之外,您已经完成了所有操作 myForm: FormGroup = this.initModelForm(); 完整代码为: 我正在记录formArray值 import { Component } fr
{fruits:Array[0]}
我所期望的是:
{fruits:Array[1]}//数组的数量取决于选中的复选框
下面是一个示例除了表单初始化之外,您已经完成了所有操作
myForm: FormGroup = this.initModelForm();
完整代码为:
我正在记录formArray值
import { Component } from '@angular/core';
import { FormGroup, FormArray, FormControl, FormBuilder } from '@angular/forms';
export interface Fruit {
uid: string;
name: string;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
public checks = [
{description: 'descr1', value: 'value1'},
{description: "descr2", value: 'value2'},
{description: "descr3", value: 'value3'}
];
myForm: FormGroup = this.initModelForm();
constructor(
public _fb: FormBuilder
) { }
initModelForm(): FormGroup{
return this._fb.group({
otherControls: [''],
myChoices: new FormArray([])
})
}
onCheckChange(event) {
console.log(event);
const formArray: FormArray = this.myForm.get('myChoices') as FormArray;
/* Selected */
if(event.target.checked){
// Add a new control in the arrayForm
formArray.push(new FormControl(event.target.value));
}
/* unselected */
else{
// find the unselected element
let i: number = 0;
formArray.controls.forEach((ctrl: FormControl) => {
if(ctrl.value == event.target.value) {
// Remove the unselected element from the arrayForm
formArray.removeAt(i);
return;
}
i++;
});
}
console.log(formArray.value);
}
}
这是一种类似Netanel Basal的方法(只更改提交功能)。如果我们以一种价值观可以是这样的形式思考,事情就会变得更具流动性
{
"otherControls": "",
"myChoices": [
false,
true,
false
]
}
好吧,我们不想要这些丑陋的数据,但我们可以,在提交时写一些类似的东西
submit(myForm) {
if (myForm.valid) {
const value = { ...myForm.value };
value.myChoices = this.checks
.filter((x, index) => myForm.value.myChoices[index])
.map(x => x.value);
this.result = value;
}
}
“结果”将是,例如
{
"otherControls": "",
"myChoices": [
"value2"
]
}
嗯,我们确实是复杂的“提交”,但在另一方面,我们的形式变得像
<form *ngIf="myForm" [formGroup]="myForm" (submit)="submit(myForm)">
<div formArrayName="myChoices">
<div *ngFor="let choice of myForm.get('myChoices').controls; let i=index" class="col-md-2">
<label>
<input type="checkbox" [formControlName]="i">
{{checks[i].description}}
</label>
</div>
</div>
<button type="submit">submit</button>
</form>
请参见可能的重复:您可能会发现这很有用:
initModelForm(): FormGroup {
return this._fb.group({
otherControls: [""],
myChoices: new FormArray(this.checks.map(x => new FormControl(false)))
});
}