0

I have a small form that has default values for some checkboxes for example, there is an person model, when the checkbox "dog" in the form generated by formly is clicked it will add to an array of "pets" the string of dog that forms part of the person model. How can I achieve this with formly?

{
     key: "dog",
     type: "checkbox",
     templateOptions: {
          ???
     }
}

Form example:

Person name: Joe
Pets:
[x] dog

This will set the model to:

 {
      "name": "Joe"
      "pets": [ "dog" ]
 }
David
  • 679
  • 1
  • 9
  • 22

1 Answers1

0

@veg, this question is for angular formly, not angular. It's different. Significantly so.

In your initialization:

vm.model = { //initialize a model with a pets property holding an empty array.
  pets: []
}

In your field model:

{
   key: 'dog',
   type: 'checkbox',
   templateOptions: {
      label: 'dog',
      onChange: function($viewValue, $modelValue, $scope) {
        if($modelValue) $scope.model.pets.push('dog'); //if it's true--add it
        else { //need to remove it from the array
           var index = $scope.model.pets.indexOf('dog'); //get the index
           $scope.model.pets.slice(index, index+1); //remove it from the array
        }
      }
   },
}
MattE
  • 1,044
  • 1
  • 14
  • 34