Angular ReactiveForms: Producing an array of checkbox values?

前端 未结 12 645
执念已碎
执念已碎 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:16

    If you want to use an Angular reactive form (https://angular.io/guide/reactive-forms).

    You can use one form control to manage the outputted value of the group of checkboxes.

    component

    import { Component } from '@angular/core';
    import { FormGroup, FormControl } from '@angular/forms';
    import { flow } from 'lodash';
    import { flatMap, filter } from 'lodash/fp';
    
    @Component({
      selector: 'multi-checkbox',
      templateUrl: './multi-checkbox.layout.html',
    })
    export class MultiChecboxComponent  {
    
      checklistState = [ 
          {
            label: 'Frodo Baggins',
            value: 'frodo_baggins',
            checked: false
          },
          {
            label: 'Samwise Gamgee',
            value: 'samwise_gamgee',
            checked: true,
          },
          {
            label: 'Merry Brandybuck',
            value: 'merry_brandybuck',
            checked: false
          }
        ];
    
      form = new FormGroup({
        checklist : new FormControl(this.flattenValues(this.checklistState)),
      });
    
    
      checklist = this.form.get('checklist');
    
      onChecklistChange(checked, checkbox) {
        checkbox.checked = checked;
        this.checklist.setValue(this.flattenValues(this.checklistState));
      }
    
      flattenValues(checkboxes) {
        const flattenedValues = flow([
          filter(checkbox => checkbox.checked),
          flatMap(checkbox => checkbox.value )
        ])(checkboxes)
        return flattenedValues.join(',');
      }
    }
    

    html

    checklistState

    Manages the model/state of the checklist inputs. This model allows you to map the current state to whatever value format you need.

    Model:

    {
       label: 'Value 1',
       value: 'value_1',
       checked: false
    },
    {
      label: 'Samwise Gamgee',
      value: 'samwise_gamgee',
      checked: true,
    },
    {
      label: 'Merry Brandybuck',
      value: 'merry_brandybuck',
      checked: false
    }
    

    checklist Form Control

    This control stores the value would like to save as e.g

    value output: "value_1,value_2"

    See demo at https://stackblitz.com/edit/angular-multi-checklist

提交回复
热议问题