简体   繁体   English

angular2-带复选框的FormArray

[英]angular2 - FormArray with Checkboxes

I have a dynamic size of items. 我有商品的动态尺寸。 For every item I want to generate a checkbox. 对于每个项目,我要生成一个复选框。 I thought the best approach for that is to use the FormArray. 我认为最好的方法是使用FormArray。

But I cannot set any additional property to specifiy the label for the dynamic checkboxes. 但是我不能设置任何其他属性来指定动态复选框的标签。

items: Array<string> = ['Banana', 'Apple', 'Beer', 'Water'];

let checkboxArray = new FormArray([]);

this.items.forEach(item => {
  let formControl = new FormControl(true);
  checkboxArray.push(formControl);
})

But as we see here, i can only specifiy the value for the checkbox in the formControl, but cannot set any additional info about the label. 但是正如我们在这里看到的,我只能在formControl中指定复选框的值,而不能设置有关标签的任何其他信息。

A working plunkr is here: http://plnkr.co/edit/ODe5QSOEvQsQiuBzs56o?p=preview 可以使用的plunkr在这里: http ://plnkr.co/edit/ODe5QSOEvQsQiuBzs56o?p=preview

Use normal FormGroup. 使用普通的FormGroup。

form: FormGroup;
items: string[] = ['Banana', 'Apple', 'Beer', 'Water'];

this.form = new FormGroup({
  checkboxes: new FormGroup({ }),
});

this.items.forEach(item => {
  this.form.controls['checkboxes'].addControl(item, new FormControl(true));
});

Loop items instead of FormArray. 循环items而不是FormArray。

<form [formGroup]="form.controls['checkboxes']">
    <div *ngFor="let item of items">
        <input type="checkbox" [formControlName]="item">
        <span>{{ item }}</span>
    </div>
</form>

Plnkr: http://plnkr.co/edit/qHjpejOhSfw25YHhJNqV?p=preview 网址: http ://plnkr.co/edit/qHjpejOhSfw25YHhJNqV?p = preview

This is another way to create dynamic checkboxes using formArray and update the formArray based on checkbox selection. 这是使用formArray创建动态复选框并根据复选框选择更新formArray的另一种方法。 For this have a extra selected property for each dynamic list 为此,为每个动态列表额外选择一个属性

component.html component.html

<div *ngFor="let item of formArray.controls;" [formGroup]="item">
    <mat-checkbox [formControl]="item.get('selected')">
          {{item.get("name")?.value}}
    </mat-checkbox>
</div>

component.ts component.ts

"items": [
{
  "name": "Banana",
  "selected": true
},
{
  "name": "Apple",
  "selected": false
}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM