【问题标题】:Angular dynamic form view from JSON data with nested condition来自具有嵌套条件的 JSON 数据的角度动态表单视图
【发布时间】:2020-01-19 02:20:39
【问题描述】:

我正在尝试使用 Json 数据制作动态表单,并且应从 JSON 数据的选项类型选择中选择条件。 JSON数据结构如下。在这种情况下,例如,从下拉菜单中选择第一个元素 A Speditions GmbH 后,该元素的子内容“label”:“Subfield1”,表单上应该会出现另一个下拉选项。

我的打字稿(更新)

import { Component, OnInit } from '@angular/core'; 
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { MatDialog, MatDialogRef } from '@angular/material';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
    form:FormGroup;
    formTemplate:any = form_template;
    stepCfg = {
      stepType: 'rahmendaten',
      stepHeading: '',
      stepIndex: 0,
      steps: [],
      firstStep: false,
      lastStep: false,
      onlyStep: false,
      data: {},
      htmlContent: ''
    };
    formDataObj = {};


  ngOnInit() {
    for (const prop of Object.keys(this.stepCfg.data)) {
      this.formDataObj[prop] = new FormControl(this.stepCfg.data[prop].value);
      this.formTemplate.push({
        key: prop,
        label: this.stepCfg.data[prop].label,
        type: this.stepCfg.data[prop].type,
        options: this.stepCfg.data[prop].options
      });
    }
   this.form = new FormGroup(this.formDataObj);
  }
}

 const form_template = [{
 "type": "select",
 "label": "Spedition",
 "options": [
 {
     "value": "sped1",
     "label": "A Speditions GmbH",
     "subfield": {
        "type": "select",
        "label": "Subfield1",
        "options": [
          {
            "value": "subfieldvalue1",
            "label": "101"
          },
        ]
        }
     },
   {
      "value": "sped2",
      "label": "Alf Scon GmbH"
   },
  {
      "value": "sped3",
      "label": "Barthtest"
  },
 ]

}]

export default form_template

//HTml

<mat-card class="rahmendaten-container">
  <h3 class="page__header">{{stepCfg.stepHeading}}</h3>
  <div *ngIf="!!stepCfg.htmlContent" [innerHTML]="stepCfg.htmlContent"> 
  </div>
  <form [formGroup]="form" autocomplete="off" (ngSubmit)="onSubmit()">
    <mat-card-content class="page">
      <div class="page__container">
        <div *ngFor="let prop of formTemplate" class="container__row">
          <div [ngSwitch]="prop.type">
            <div *ngSwitchCase="'select'">
              <span [innerHTML]="prop.label" class="container__row__label"> 
              </span>
             <mat-form-field>
                <mat-select>
                  <mat-option *ngFor="let option of prop.options" 
                  [value]="option.value">{{option.label}}</mat-option>
                  </mat-select>
             </mat-form-field>
            </div>
          </div>
        </div>
      </div>
    </mat-card-content>
   </form>
  </mat-card>

【问题讨论】:

  • 你需要写一个问题。完成任务的哪一部分有问题?
  • @Vato 我必须实现条件在这种情况下,例如,在从下拉列表中选择第一个元素 A Speditions GmbH 后,该元素的子内容“label”:“Subfield1”,以及另一个下拉选项应该出现在表单上。

标签: javascript json angular typescript


【解决方案1】:

因为您的代码中没有太多内容。你需要做更多的工作。我只会给你建议做什么。

检查反应式表单或模板驱动表单。我推荐反应形式。

实际上,您可以将表单转换为反应式表单。

form_template = [{
    "type": "select",
    "label": "Spedition",
    "options": [
      {
        "value": "sped1",
        "label": "Adrian Speditions GmbH",
        "subfield": {
          "type": "select",
          "label": "Subfield1",
          "options": [
            {
              "value": "subfieldvalue1",
              "label": "101"
            },
          ]
        }
      },
      {
        "value": "sped2",
        "label": "Alfred Schuon GmbH"
      }
    ]
  }]

反应形式看起来像:

reactiveForm: FormGroup;

this.reactiveForm = new FormGroup({
  type: new FormControl('select'),
  label: new FormControl('Spedition'),
  options: new FormArray([
    new FormGroup({
      value: new FormControl('sped1'),
      label: new FormControl('Adrian Speditions GmbH'),
      subfield: new FormGroup({
        type: new FormControl('select'),
        label: new FormControl('Subfield1'),
        options: new FormArray([
          new FormGroup({
            value: new FormControl('subfieldvalue1'),
            label: new FormControl('101')
          })
        ])
      })
    })
  ])
});

您可以像这样访问和更改 TS 中的值。

this.reactiveForm.get('options').at(indexOfArray).get('value').setValue('Your New Value');

因为你想使用选择。这是使用反应形式的角度材料网页的示例。 检查:https://material.angular.io/components/select/examples 这也是我的动态表单问题,它也可能有所帮助。

<h4>mat select</h4>
<mat-form-field>
  <mat-label>Favorite animal</mat-label>
  <mat-select [formControl]="animalControl" required>
    <mat-option>--</mat-option>
    <mat-option *ngFor="let animal of animals" [value]="animal">
      {{animal.name}}
    </mat-option>
  </mat-select>
  <mat-error *ngIf="animalControl.hasError('required')">Please choose an animal</mat-error>
  <mat-hint>{{animalControl.value?.sound}}</mat-hint>
</mat-form-field>

要将 select 绑定到表单,您需要在 html 中指定要绑定的 formArray、formgroup 和 formControl。

在这种情况下 formControl 是 animalControl。但对你来说,它可能会通过标签或类型。但您还需要指定它们所在的 formGroup 或 FormArray。

设置所有表单后。您可以使用 *ngIf 检查 formvalue 是否为空。如果没有,您可以向您展示下一个选择。这就是我能提供的全部帮助。

nested custom FormArray component doesn't bind with child form with FormArrayName

您还可以使用 formbuilder 并添加验证器。您现在只需要对响应式表单进行更多研究。

祝你好运!

【讨论】:

  • 谢谢@Vato,我已经更新了代码,请看一下。
猜你喜欢
  • 1970-01-01
  • 2018-10-26
  • 2018-07-27
  • 2015-09-26
  • 2019-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多