从 JSON Schema 动态创建表单

问题描述 投票:0回答:4

我正在努力从 Angular 8 中的 JSON Schema 创建动态表单。我找到了一些库,但是 其中一个非常旧(最后一次提交约为 2 年前)并且从今年开始它的分支

我不想使用第一个,因为 Angular 8 已弃用它,所以我选择第二个。我遇到了麻烦,因为这个项目不在任何 npm 存储库上,只在 github 上。我从 git 下载了它,如下所示:

npm i rhalff/angular2-json-schema-form#angular-8

当我开始使用此依赖项构建我的项目并将导入附加到

app.module.ts
后,结果如下:

ERROR in src/app/app.module.ts:20:65 - error TS2307: Cannot find module 'angular2-json-schema-form'.

我发现在

node_module
中没有任何src或dist文件夹,然后我查看了github projecet,发现在
/.npmignore
中有一个src。

我对此有一些解决方案,但这不是最终的解决方案,我认为这是一个非常糟糕的主意。 我将在本地克隆 git 存储库,然后使用

npm run build
构建它,然后使用
npm link
然后在项目目录中
npm link <someName>

这个问题有解决办法吗?或者任何其他用于将 JSON 模式转换为 Angular 8 表单的库?

javascript angular npm angular8
4个回答
9
投票

您可以考虑使用Formly,它支持

json-schema
,并且它提供了很多入门示例https://formly.dev/examples/advanced/json-schema


0
投票

你可以做这样的事情。它可能无法涵盖一些复杂的场景,但可以用不太复杂的形式发挥作用。

形式.ts

public form: FormGroup = new FormGroup({});
public fields = [
  {label: 'Full Name', name: 'full_name', type: 'text'},
  {label: 'Email', name: 'email', type: 'email'},
  {label: 'Comments', name: 'comments', type: 'textarea'},
]

constructForm(){
    let controls = {};
    fields.map(field => {
       controls[field.name] = new FormControl('');
    });
    this.form = new FormGroup(controls);
  }

form.html

   <form [formGroup]="form">
     <div *ngFor="let field of fields">
       <label for="{{field.name}}">{{field.label}}</label>
       <div [ngSwitch]="field.type">
    
          <!-- textarea -->
          <textarea *ngSwitchCase="'textarea'" [formControlName]="field.name"></textarea>
    
          <!-- other input fields (text, password, number, email) -->
          <input *ngSwitchDefault id="{{field.id}}" type="{{field.type || 'text'}}" [formControlName]="field.name" />
        </div>
     </div>
   </form>

这只是我的做法的基本结构。您可以向字段对象添加更多道具,甚至是“更改时”处理函数并玩更多。即 css_classes、maxlength,并且可以在 html 中执行类似

field.propName

的操作

喜欢:

{label: 'Complex Field', name: 'complex_field, type: 'text', onChange: () => {console.log("Something Happened")}}

还有

<input type="{{field.type}} (change)="field.onChange()" [formControlName]="field.name" />

祝你好运


0
投票

您可以查看 https://surveyjs.io/ 这是一组客户端 JavaScript 库,可生成并使用 JSON 来表示表单架构和响应。它们在 GitHub 上开源,您可以将它们安装为 npm 包,以便在您自己的环境中试用它们。他们还提供了大量的例子。


-1
投票

您可以使用动态表单模式。它完全基于模式,并提供在模式中添加验证、条件验证和下拉条件选项的选项。 有关更多详细信息,请查看链接:基于架构的快速 Angular Reactive Form 组件开发

© www.soinside.com 2019 - 2024. All rights reserved.