我使用https://coryrylan.com/blog/creating-a-dynamic-checkbox-list-in-angular 作为动态添加复选框列表的参考。
我的表单结构如下:
userForm:new FormGroup({
attributes: new FormGroup({
roles:new FormArray([])
})
})
根据该链接中的addCheckboxlist,我改写为
private addCheckboxes() {
this.roles.map((o, i) => {
const control = new FormControl(i === 0);
((this.userForm.controls.attributes as FormGroup).controls.roles as FormArray).push(control);
});
}
现在,我不确定如何在html中循环获取这些复选框。请协助。
编辑: 在TS中:
rolesInCompany=[{
id:"org1",
name:"ABC"
},{
id:"org2",
name:"DEF"
}];
在HTML中:
<label formArrayName="roles" *ngFor="let role of userForm.controls.attributes.controls.roles.controls; let i = index">
<input type="checkbox" [value]="rolesInCompany[i].name" [formControl]="role">
{{rolesInCompany[i].name}}
</label>
提交后,我同时获得以下角色:Array [true,true]。我需要输入姓名。
答案 0 :(得分:0)
您问题中的链接包含Stackblitz中的代码演示
https://stackblitz.com/edit/angular-stszta
app.component.html 是
<form [formGroup]="form" (ngSubmit)="submit()">
<label formArrayName="orders" *ngFor="let order of form.controls.orders.controls; let i = index">
<input type="checkbox" [formControlName]="i">
{{orders[i].name}}
</label>
<div *ngIf="!form.valid">At least one order must be selected</div>
<br>
<button [disabled]="!form.valid">submit</button>
</form>
答案 1 :(得分:0)
您可以尝试使用HTML本身的模板
<input type="checkbox" *ngFor="let checkbox of checkboxes" value="{{checkbox}}" />