基于 JSON Schema,如何递归创建嵌套 FormGroup 与 FormArray?

解读

国内中高级 Angular 面试常把「动态表单」作为分水岭:既能考察候选人对 Reactive Forms 的掌握深度,又能验证其对 JSON Schema 的理解与递归思维。
面试官真正想看的是:

  1. 你能否把 JSON Schema 的 type、properties、items、required 等关键字映射成 FormGroup / FormArray;
  2. 递归边界与异常处理是否严谨;
  3. 是否熟悉 TypeScript 类型收窄 与 AOT 友好 的写法;
  4. 对性能与可维护性有无工程化思考(如懒加载 Validator、按需订阅)。
    一句话:用 Schema 驱动,一行代码不写死,递归生成整棵 Form 树。

知识点

  • JSON Schema 核心字段:type、properties、items、required、$ref、allOf、oneOf
  • Angular Reactive Forms:FormBuilder、FormGroup、FormArray、FormControl、AbstractControl
  • 递归下降算法:深度优先遍历 Schema 节点,遇到 object → FormGroup,array → FormArray,primitive → FormControl
  • Validator 工厂:根据 Schema 的 minimum、maxLength、pattern 等同步创建 Validators.compose()
  • AOT 与类型安全:用自定义 type guard 收窄 SchemaNode 类型,避免 any
  • 循环引用与$ref:用 WeakMap 做已建控件缓存,防止无限递归
  • 变更策略:OnPush + trackBy 减少递归带来的脏检查
  • 国内实战:后端常返回 OpenAPI / Swagger JSON,直接当 Schema 用,需兼容 中文字段名 与 拼音缩写 key

答案

核心思路:“Schema 节点类型决定控件类型”,代码分三层:

  1. 类型守卫与工具函数
  2. 递归工厂
  3. 对外暴露的 buildFormFromSchema()
/* 1. 类型守卫 */
type PrimitiveType = 'string' | 'number' | 'integer' | 'boolean';
interface ObjectSchema {
  type: 'object';
  properties: Record<string, any>;
  required?: string[];
}
interface ArraySchema {
  type: 'array';
  items: any;
}
type Schema = ObjectSchema | ArraySchema | { type: PrimitiveType };

const isObjectSchema = (s: any): s is ObjectSchema => s.type === 'object';
const isArraySchema  = (s: any): s is ArraySchema  => s.type === 'array';
const isPrimitive    = (s: any) => ['string','number','integer','boolean'].includes(s.type);

/* 2. Validator 工厂 */
function createValidators(schema: any): ValidatorFn[] {
  const v: ValidatorFn[] = [];
  if (schema.required) v.push(Validators.required);
  if (schema.minLength) v.push(Validators.minLength(schema.minLength));
  if (schema.pattern)   v.push(Validators.pattern(new RegExp(schema.pattern)));
  /* 更多规则同理 */
  return v;
}

/* 3. 递归工厂 */
export class SchemaFormFactory {
  private cache = new WeakMap<any, AbstractControl>(); // 解决$ref循环

  build(schema: Schema): AbstractControl {
    if (this.cache.has(schema)) return this.cache.get(schema)!;

    let control: AbstractControl;

    if (isObjectSchema(schema)) {
      const group: Record<string, AbstractControl> = {};
      Object.keys(schema.properties).forEach(key => {
        const subSchema = schema.properties[key];
        const required  = schema.required?.includes(key) ?? false;
        const subControl = this.build({ ...subSchema, required });
        group[key] = subControl;
      });
      control = new FormGroup(group);
    }
    else if (isArraySchema(schema)) {
      const arr = new FormArray<AbstractControl>([]);
      /* 国内常见:数组长度默认0,用户点击“添加”时再 push */
      this.cache.set(schema, arr); // 提前缓存,防止items自引用
      /* 若需默认一条,可取消注释 */
      // arr.push(this.build(schema.items));
      control = arr;
    }
    else if (isPrimitive(schema)) {
      const v = createValidators(schema);
      control = new FormControl({ value: '', disabled: false }, v);
    } else {
      throw new Error(`未支持的Schema类型`);
    }

    this.cache.set(schema, control);
    return control;
  }
}

/* 4. 对外API */
export function buildFormFromSchema(schema: Schema): FormGroup {
  const factory = new SchemaFormFactory();
  return factory.build(schema) as FormGroup;
}

使用示例(组件层)

export class DynamicHostComponent implements OnInit {
  form!: FormGroup;

  ngOnInit() {
    const schema: ObjectSchema = {
      type: 'object',
      properties: {
        user: {
          type: 'object',
          properties: {
            name: { type: 'string', required: true, minLength: 2 },
            age : { type: 'integer', required: true, minimum: 18 }
          },
          required: ['name','age']
        },
        hobbies: {
          type: 'array',
          items: { type: 'string', minLength: 1 }
        }
      },
      required: ['user']
    };
    this.form = buildFormFromSchema(schema);
  }

  addHobby() {
    const hobbies = this.form.get('hobbies') as FormArray;
    hobbies.push(new FormControl('', Validators.required));
  }
}

模板层用 *ngFor + formGroupName / formArrayName 递归嵌套即可,不再赘述。
关键点:整棵树由 Schema 唯一驱动,后端改字段、改校验规则,前端零改动。

拓展思考

  1. 异步校验:Schema 里加 async: { url: '/check-unique' },工厂层返回 AsyncValidatorFn,用 switchMap + debounce 防止密集请求。
  2. 条件渲染:利用 allOf/oneOf 生成 隐藏式 FormGroup,通过 valueChanges 动态增删控件,实现 “选择证件类型→出现对应输入框” 这类国内高频需求。
  3. 国际化:在 Schema 同级放 i18n: { zh: '姓名', en: 'Name' },工厂同步产出 labelMap,模板用 {{ labelMap[key] | translate }} 直接绑定。
  4. 性能优化:
    • 对超长表格数组使用 虚拟滚动(cdk-virtual-scroll-viewport)+ trackBy;
    • 对深层嵌套开启 OnPush,并在工厂层统一 markForCheck;
    • 用 WeakRef 清理缓存,防止内存泄漏。
  5. 服务端渲染:Angular Universal 下避免在构造函数里访问 window,工厂层所有正则、日期校验用 isPlatformBrowser 包裹,确保 首屏无报错。
  6. 低代码平台:把上述工厂封装成 Angular Library,上传 Schema → 自动生成表单 → 在线配置校验 → 导出 Vue/React 版本,成为国内 SaaS 的 “动态表单引擎” 核心卖点。