Angular ReactiveForms: Producing an array of checkbox values?

前端 未结 12 662
执念已碎
执念已碎 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条回答
  •  生来不讨喜
    2020-11-29 18:02

    If you are looking for checkbox values in JSON format

    { "name": "", "countries": [ { "US": true }, { "Germany": true }, { "France": true } ] }
    

    Full example here.

    I apologise for using Country Names as checkbox values instead of those in the question. Further explannation -

    Create a FormGroup for the form

     createForm() {
    
        //Form Group for a Hero Form
        this.heroForm = this.fb.group({
          name: '',
          countries: this.fb.array([])
        });
    
        let countries=['US','Germany','France'];
    
        this.setCountries(countries);}
     }
    

    Let each checkbox be a FormGroup built from an object whose only property is the checkbox's value.

     setCountries(countries:string[]) {
    
        //One Form Group for one country
        const countriesFGs = countries.map(country =>{
                let obj={};obj[country]=true;
                return this.fb.group(obj)
        });
    
        const countryFormArray = this.fb.array(countriesFGs);
        this.heroForm.setControl('countries', countryFormArray);
      }
    

    The array of FormGroups for the checkboxes is used to set the control for the 'countries' in the parent Form.

      get countries(): FormArray {
          return this.heroForm.get('countries') as FormArray;
      };
    

    In the template, use a pipe to get the name for the checkbox control

      
    {{key.key}}

提交回复
热议问题