You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据Formly中field1的取值更新field2的下拉选项?

如何根据Formly中field1的选择值更新field2的下拉选项?

先看你给出的Formly表单代码:

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: [],
    },
  },
];

实现方案

直接在field1的change回调里处理逻辑即可,无需嵌套valueChanges订阅(避免重复订阅引发内存泄漏),具体步骤如下:

  1. 获取field2的字段配置项
  2. 根据field1的选中值,同步或异步更新field2的下拉选项

情况1:同步生成选项(本地数据映射)

如果field2的选项可以根据field1的值直接从本地数据生成:

formGroup = new FormGroup({});
modela!: any;
fieldsa: FormlyFieldConfig[] = [
  {
    key: 'field1',
    type: 'select',
    props: {
      label: 'Field1',
      options: this.someService.getData(),
      // 直接使用change回调的value参数,无需额外订阅valueChanges
      change: (field) => {
        const selectedValue = field.formControl?.value;
        // 找到field2的配置项
        const field2 = this.fieldsa.find(f => f.key === 'field2');
        if (field2) {
          // 根据选中值生成对应选项
          field2.props.options = this.getField2Options(selectedValue);
        }
      },
    },
  },
  {
    key: 'field2',
    type: 'select',
    props: {
      label: 'Field2',
      options: [],
    },
  },
];

// 示例:根据field1的值返回对应选项集合
private getField2Options(field1Value: any) {
  const optionMap = {
    'option1': [{ label: '选项A', value: 'a' }, { label: '选项B', value: 'b' }],
    'option2': [{ label: '选项X', value: 'x' }, { label: '选项Y', value: 'y' }],
  };
  return optionMap[field1Value] || [];
}

情况2:异步从服务获取选项

如果field2的选项需要通过API接口根据field1的值动态获取:

formGroup = new FormGroup({});
modela!: any;
// 用于销毁时取消订阅,避免内存泄漏
private destroy$ = new Subject<void>();

fieldsa: FormlyFieldConfig[] = [
  {
    key: 'field1',
    type: 'select',
    props: {
      label: 'Field1',
      options: this.someService.getData(),
      change: (field) => {
        const selectedValue = field.formControl?.value;
        const field2 = this.fieldsa.find(f => f.key === 'field2');
        if (field2 && selectedValue) {
          // 调用服务获取选项,用takeUntil确保组件销毁时取消订阅
          this.someService.getField2Options(selectedValue)
            .pipe(takeUntil(this.destroy$))
            .subscribe({
              next: (options) => {
                field2.props.options = options;
              },
              error: () => {
                field2.props.options = []; // 接口出错时清空选项
              }
            });
        } else {
          field2?.props.options = []; // 未选中值时清空选项
        }
      },
    },
  },
  {
    key: 'field2',
    type: 'select',
    props: {
      label: 'Field2',
      options: [],
    },
  },
];

ngOnDestroy() {
  this.destroy$.next();
  this.destroy$.complete();
}

关键注意事项

  • 不要在change回调中重复订阅valueChanges,否则每次触发change都会新增订阅,引发内存泄漏
  • 更新props.options后,Formly会自动刷新field2的下拉列表;若遇到不刷新的情况,可手动调用changeDetectorRef.markForCheck()触发变更检测
  • 异步请求必须在组件销毁时取消订阅,避免内存泄漏

内容的提问来源于stack exchange,提问作者Mario

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 15:25:18