我正在尝试通过 angular 表单生成器发送多个复选框,但它不起作用
I'm trying to send multiple checkboxes through angular form builder but its not working
当我运行此代码时,复选框在前端不可见。我想要做的是从用户那里获取多个复选框输入并将其发送到 api。请为此提供帮助。
<form [formGroup]="form" (submit)="submit(form.value)">
<div *ngFor="let addon of addOns; let i = index">
<input type="checkbox" [formControl] ="addOn">
{{user.addOns[i].name}}
</div>
<button type="submit">
Calculate Premium
</button>
</form>
{{ form.value | json }}
这是组件 class 数据未与表单控件名称绑定 - 谁能告诉我我在这方面做错了什么
export class FourWheelerComponent implements OnInit {
user ={
addOns:[
{name:'IsValidDrivingLicense', selected:true, id:1},
{name:'IsMoreThanOneVehicle', selected:false, id:2},
{name:'IsNoPrevInsurance', selected:false, id:3},
{name:'IsTransferOfNCB', selected:false, id:4}
]
}
form;
constructor(private fb: FormBuilder,
private _quoteService: QuoteService) {
console.clear();
this.form = this.fb.group({
addOns:this.buildAddOns()
});
console.log(this.form.get("addOns"))
}
ngOnInit() {
}
getAddOns(): FormArray{
return this.form.get('addOns') as FormArray;
};
buildAddOns(){
const arr = this.user.addOns.map(s=>{
return this.fb.control(s.selected,);
})
return this.fb.array(arr);
}
submit(value){
const f = Object.assign({}, value, {
addOns: value.addOns.map((s,i) =>{
return{
name: this.user.addOns[i].name,
selected:s,
}
})
});
console.log(f);
}
}
问题出在您编写的 getAddOns()
的 get 函数中,它应该是 get addOns()
,因为它是 getter 函数,我们在创建表单组时正在使用它,在这一行 addOns:this.buildAddOns()
我试过代码只是为了检查,
在 https://stackblitz.com/edit/angular-forms-checkbox 上,您可以查看它。
当我运行此代码时,复选框在前端不可见。我想要做的是从用户那里获取多个复选框输入并将其发送到 api。请为此提供帮助。
<form [formGroup]="form" (submit)="submit(form.value)">
<div *ngFor="let addon of addOns; let i = index">
<input type="checkbox" [formControl] ="addOn">
{{user.addOns[i].name}}
</div>
<button type="submit">
Calculate Premium
</button>
</form>
{{ form.value | json }}
这是组件 class 数据未与表单控件名称绑定 - 谁能告诉我我在这方面做错了什么
export class FourWheelerComponent implements OnInit {
user ={
addOns:[
{name:'IsValidDrivingLicense', selected:true, id:1},
{name:'IsMoreThanOneVehicle', selected:false, id:2},
{name:'IsNoPrevInsurance', selected:false, id:3},
{name:'IsTransferOfNCB', selected:false, id:4}
]
}
form;
constructor(private fb: FormBuilder,
private _quoteService: QuoteService) {
console.clear();
this.form = this.fb.group({
addOns:this.buildAddOns()
});
console.log(this.form.get("addOns"))
}
ngOnInit() {
}
getAddOns(): FormArray{
return this.form.get('addOns') as FormArray;
};
buildAddOns(){
const arr = this.user.addOns.map(s=>{
return this.fb.control(s.selected,);
})
return this.fb.array(arr);
}
submit(value){
const f = Object.assign({}, value, {
addOns: value.addOns.map((s,i) =>{
return{
name: this.user.addOns[i].name,
selected:s,
}
})
});
console.log(f);
}
}
问题出在您编写的 getAddOns()
的 get 函数中,它应该是 get addOns()
,因为它是 getter 函数,我们在创建表单组时正在使用它,在这一行 addOns:this.buildAddOns()
我试过代码只是为了检查,
在 https://stackblitz.com/edit/angular-forms-checkbox 上,您可以查看它。