Remove value from the model for dynamically disabled (via `expressionProperties`) field?

1.9k views Asked by At

When an angular-formly (I am using v6.4.x w/ AngularJS 1.2.x) field's expression property causes the field to dynamically toggle between enabled and disabled, a switch to disabled does not remove any previously entered value for that field from the model. For example:

  1. Using the advanced layout example from Formly
  2. Enter a first name, such that the last name is enabled
  3. Enter value for last name
  4. Remove the first name value such that last name is again disabled
  5. Notice that the model still contains the data entered for last name even though it is disabled

Given how disabled works for standard HTML form submission, I would expect the model to no longer contain a value for that field.

I need to avoid submitting data for a field that has been disabled, so if this is intended behavior (and I don't know that it is...), can someone offer thoughts on how to accomplish the removal of a value whenever expressionProperties causes a field to be disabled?

1

There are 1 answers

0
JAAulde On BEST ANSWER

kentcdodds' comments got me moving in the right direction and able to find enough pieces in the docs to make something work. In my most immediate task I was needing a radio option to get removed from the model when disabled, and I ended up unchecking it too. I did this by extending the radio input type and adding a link function for access to scope and the element. Below is something along the lines of what it looks like:

app.config(['formlyConfigProvider', function (formlyConfigProvider) {
    formlyConfigProvider.setType({
        name: 'liveDisableRadio',
        extends: 'radio',
        link: function (scope, element) {
            scope.$watch('to.disabled', function (is_disabled) {
                if (is_disabled) {
                    delete scope.model[scope.options.key];
                    element.find(':radio:checked').prop('checked', false).trigger('change');
                }
            });
        }
    });
}])