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.

Yehuda
  • 41
  • 5
  • I think the `model` part is static, but I do not see your issue here. Please produce a [mcve] reproducing your issue. –  May 23 '22 at 14:23

1 Answers1

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

Hau Nguyen
  • 76
  • 2