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

Angular Schema Form数组默认渲染2个元素的实现方法咨询

如何让评论数组默认渲染2个元素

嘿,我懂你的需求——就是想让这个评论表单一开始就默认显示2个完整的评论输入条目,对吧?你之前尝试的minItems和maxItems其实是数据验证规则,它们只负责校验用户提交的数据是否符合数量要求,并不会控制表单初始渲染的元素数量,所以没达到预期效果很正常~

要实现默认渲染2个元素,你需要给comments数组添加default属性,直接传入2个符合子对象结构的初始数据。下面是修改后的完整Schema:

{
  "type": "object",
  "title": "Comment",
  "required": [ "comments" ],
  "properties": {
    "comments": {
      "type": "array",
      "default": [
        {
          "name": "",
          "email": "",
          "spam": true,
          "comment": ""
        },
        {
          "name": "",
          "email": "",
          "spam": true,
          "comment": ""
        }
      ],
      "items": {
        "type": "object",
        "properties": {
          "name": { "title": "Name", "type": "string" },
          "email": {
            "title": "Email",
            "type": "string",
            "pattern": "^\\S+@\\S+$",
            "description": "Email will be used for evil."
          },
          "spam": { "title": "Spam", "type": "boolean", "default": true },
          "comment": {
            "title": "Comment",
            "type": "string",
            "maxLength": 20,
            "validationMessage": "Don't be greedy!"
          }
        },
        "required": [ "name", "comment" ]
      }
    }
  }
}

关键点说明:

  • 给comments数组添加的default数组里,每个对象都遵循子Schema的结构,甚至可以预设一些默认值(比如spam已经默认是true,这里也保留了)
  • 原来的验证规则(比如required、子对象的必填项、maxLength等)依然完全生效,不会受到默认值的影响
  • 大部分基于JSON Schema的表单渲染库都会识别这个default属性,自动渲染对应数量的初始条目

这样设置后,表单加载时就会默认显示2个评论输入框,正好满足你的需求啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:17:55