Search code examples
angular-formly

How can I lay out sub-fields that depend on a main field?


I have a wireframe that I need to implement with ngx-formly similar to this, using Angular Material:

Nested fields layout

I have figured out how to enable and disable appropriately, but I'm not sure how to get Field 2 to sit underneath Field 1 Option A. Is this possible, and if so what is the best way to do it? I'm fairly new to Formly, so any help would be much appreciated.


Solution

  • Many thanks to aitboudad on Github for providing an answer: https://github.com/formly-js/ngx-formly/issues/1122

    His StackBlitz: https://stackblitz.com/edit/angular-hf3y6f

    Essentially, the solution is to create separate field definitions for each option of Field 1, but give them the same keys and names. They will then bind to the same thing in the model. I defined the radio buttons field using the templateOptions.options array for each choice rather than thinking to do it this way. From the StackBlitz cited above:

    {
      key: 'Field1',
      type: 'radio',
      name: 'Field1',
      templateOptions: {options: [{ value: 1, label: 'Field 1 (option1)' }]},
    },
    {
      key: 'Field2',
      type: 'input',
      className: 'ml-5 d-block',
      templateOptions: { label: 'Field 2' },
      expressionProperties: {
        'templateOptions.disabled': 'model.Field1 !== 1',
      },
    },
    {
      key: 'Field1',
      type: 'radio',
      name: 'Field1',
      templateOptions: {options: [{ value: 2, label: 'Field 1 (option2)' }]},
    },
    ....