2

I have 2 Formly forms in my app.

I need to hide a field of one form, due the value of a field in the another one.

Formly documentation gives this option (https://formly.dev/examples/field-options/hide-fields): hideExpression: '!model.name'

But I need something like: hideExpression: '!anotherModel.name'

export class AppComponent {
  form = new FormGroup({});
  model: any = {};
  options: FormlyFormOptions = {};

  fields: FormlyFieldConfig[] = [
    {
      key: 'iLikeTwix',
      type: 'checkbox',
      templateOptions: {
        label: 'I like twix',
      },
      hideExpression: '!model2.name',
    },
  ];
 form2 = new FormGroup({});
  model2: any = {};
  options2: FormlyFormOptions = {};

  fields2: FormlyFieldConfig[] = [
    {
      key: 'name',
      type: 'input',
      templateOptions: {
        label: 'Name'
      },
    }
  ];
}

Notice the line: hideExpression: '!model2.name', it is what I want to do.

Can I do it?

Thanks.

1
  • I think the model part is static, but I do not see your issue here. Please produce a minimal reproducible example reproducing your issue.
    – user17740968
    May 23, 2022 at 14:23

1 Answer 1

2

The form was bound to the model when you using this <formly-form [model]="model" [fields]="fields" [options]="options" [form]="form"></formly-form>. So Formly doesn't know about another model

You can use FormlyOptions to bind the hide expression with other variables

 public options: FormlyFormOptions = {
    formState: {
      hideCheckbox: false
    }
  }

And in fieldConfig

fields: FormlyFieldConfig[] = [
    {
      key: 'iLikeTwix',
      type: 'checkbox',
      templateOptions: {
        label: 'I like twix',
      },
      hideExpression: '!formState.hideCheckbox',
    },
  ];

In ts fille, you can change the hideCheckbox variable to whatever you want, as well as subscribe to an input change, like

fields2: FormlyFieldConfig[] = [
    {
      key: 'name',
      type: 'input',
      templateOptions: {
        label: 'Name'
      },
     hooks: {
      onInit: field => {
        return field.formControl.valueChanges
          .pipe(tap((value) => this.options.formState.hideCheckbox = Boolean(value)));
      }
     }
    }
  ];

Check here https://stackblitz.com/edit/angular-znqbmj?file=src/app/app.component.ts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.