0

In a form similar to this

formGroup = new FormGroup({});
  modela!: any;
  fieldsa: FormlyFieldConfig[] = [
    {
      key: 'field1',
      type: 'select',
      props: {
        label: 'Field1',
        options: this.someService.getData(),
        change: (field) => {
          field.formControl?.valueChanges.subscribe({
            next: (value) => {},
          });
        },
      },
    },
    {
      key: 'field2',
      type: 'select',
      props: {
        label: 'Field2',
        options: [],
      },
    },
  ];

How to get the option values of the keyed field field2 to update based on the emitted value of field1?

1 Answer 1

0

The way to solve this problem is by implementing cascading dropdown fields. The target control subscribes to the onInit hook. Here, through field, the value of the options property is updated by the value obtained from a call to a service with the value of the other control selected as an argument.

formGroup = new FormGroup({});
model!: { field1: ""; field2: "" };
fieldsa: FormlyFieldConfig[] = [
  {
    key: "field1",
    type: "select",
    props: {
      label: "Field 1",
      options: this.someService.getField1Data(),
    },
  },
  {
    key: "field2",
    type: "select",
    props: {
      label: "Field 2",
      options: [],
    },
    hooks: {
      onInit: (field) => {
        field.props!.options = field.form?.valueChanges.pipe(
          switchMap((value) => this.someService.getField2Data(value))
        );
      },
    },
  },
];

You can see an example in this post https://egghead.io/lessons/angular-implement-cascading-dropdown-fields-with-angular-formly

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.