Angular ReactiveForms: Producing an array of checkbox values?

前端 未结 12 664
执念已碎
执念已碎 2020-11-29 17:16

Given a list of checkboxes bound to the same formControlName, how can I produce an array of checkbox values bound to the formControl, rather than s

12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 18:06

    Here's a good place to use the FormArray https://angular.io/docs/ts/latest/api/forms/index/FormArray-class.html

    To start we'll build up our array of controls either with a FormBuilder or newing up a FormArray

    FormBuilder

    this.checkboxGroup = _fb.group({
      myValues: _fb.array([true, false, true])
    });
    

    new FormArray

    let checkboxArray = new FormArray([
      new FormControl(true),
      new FormControl(false),
      new FormControl(true)]);
    
    this.checkboxGroup = _fb.group({
      myValues: checkboxArray
    });
    

    Easy enough to do, but then we're going to change our template and let the templating engine handle how we bind to our controls:

    template.html

    Here we're iterating over our set of FormControls in our myValues FormArray and for each control we're binding [formControl] to that control instead of to the FormArray control and

    {{checkboxGroup.controls['myValues'].value}}
    produces true,false,true while also making your template syntax a little less manual.

    You can use this example: http://plnkr.co/edit/a9OdMAq2YIwQFo7gixbj?p=preview to poke around

提交回复
热议问题