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

如何禁用Angular Formly中的所有表单控件?

如何禁用Formly表单的所有控件

针对你的长Formly表单,不需要逐个字段手动设置disabled: true,这里有几种高效的实现方式:

方法一:给表单配置函数添加开关参数,递归遍历字段禁用

修改你的directoryForm函数,新增一个isDisabled参数,再通过递归函数遍历所有嵌套字段,统一设置禁用状态:

// 定义递归处理字段的工具函数
function disableAllFields(fields: FormlyFieldConfig[], isDisabled: boolean) {
  fields.forEach(field => {
    // 给当前字段设置禁用状态
    if (field.templateOptions) {
      field.templateOptions.disabled = isDisabled;
    } else {
      field.templateOptions = { disabled: isDisabled };
    }

    // 递归处理子字段组
    if (field.fieldGroup) {
      disableAllFields(field.fieldGroup, isDisabled);
    }
  });
}

export function directoryForm(
  countries: CountryModel[],
  dealers: DealerModel[],
  translate: TranslateService,
  isDisabled = false // 新增禁用开关参数,默认启用编辑状态
): FormlyFieldConfig[] {
  const fields = [
    // 原有的表单字段配置(保持不变)
  ];

  // 如果需要禁用,批量处理所有字段
  if (isDisabled) {
    disableAllFields(fields, isDisabled);
  }

  return fields;
}

使用时,详情视图调用:

// 详情页面加载禁用状态的表单
this.fields = directoryForm(countries, dealers, translate, true);

方法二:利用Formly的formState统一控制

Formly支持通过formState全局控制字段状态,无需修改表单配置函数,仅在组件中设置即可:

  1. 在组件中定义formState:
export class DirectoryDetailComponent {
  form = new FormGroup({});
  model = {};
  fields = directoryForm(countries, dealers, translate);
  
  // 初始化时设置全局禁用
  formState = { disabled: true };
}
  1. 在模板中绑定formState:
<form [formGroup]="form">
  <formly-form
    [form]="form"
    [fields]="fields"
    [model]="model"
    [formState]="formState"
  ></formly-form>
</form>
  1. (可选)如果自定义字段未自动读取formState,可以给所有字段添加表达式关联:
function bindDisableToFormState(fields: FormlyFieldConfig[]) {
  fields.forEach(field => {
    field.expressionProperties = {
      ...field.expressionProperties,
      'templateOptions.disabled': 'formState.disabled'
    };

    if (field.fieldGroup) {
      bindDisableToFormState(field.fieldGroup);
    }
  });
}

方法三:使用Formly扩展实现全局禁用逻辑

如果需要在多个页面复用禁用逻辑,可以创建一个Formly扩展:

import { FormlyExtension } from '@ngx-formly/core';

export const DisableAllExtension: FormlyExtension = {
  prePopulate(field) {
    // 根据formState判断是否禁用字段
    if (field.parent?.formState?.disabled) {
      field.templateOptions = {
        ...field.templateOptions,
        disabled: true
      };
    }
  },
};

在模块中注册扩展:

@NgModule({
  imports: [
    FormlyModule.forRoot({
      extensions: [
        { name: 'disable-all', extension: DisableAllExtension },
      ],
    }),
  ],
})
export class AppModule {}

之后在任意组件中只需设置formState.disabled = true,即可自动禁用所有字段。


内容的提问来源于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 23:10:25