将输入分组为数组

时间:2018-11-21 17:30:28

标签: angular typescript angular2-forms angular-reactive-forms angular-forms

我正在使用角度动态形式进行角度应用。.在这里,我正在创建具有选择框的形式。

在单击选择框时,我要生成需要排列的输入框。

这里甚至无法生成文本框。

HTML

<div *ngFor="let item of array">
        {{item.value}} is the parent
  <div *ngFor="let child of item.templateChild">
    {{child.property_name}}
    <input type="text" [value]="child.property_name">
        <div *ngFor="let partThree of questionsParthree">
            <ng-container>
            <app-question [question]="partThree" [form]="formPartThree"></app-question>

        </ng-container>
    </div>
    </div>
  </div>

TS:

  this.questionsPartThree = this.service.getQuestions(element);
        console.log(values);

  this.formPartThree = this.qcs.toFormGroup(this.questionsPartThree);
  this.formJoin = new FormGroup({ form1: this.form, form2: this.formPartTwo, template_data: this.formPartThree });

尝试在上面列出的html中制作formArray,但我收到的错误是cannot find control name template_properties

为了使您困惑并提出一个不清楚的问题,我减少了代码以及演示中将得到的所有内容。

有效的堆叠闪电战: https://stackblitz.com/edit/angular-x4a5b6-wyqdzn

表格的当前输出为

{
  "form1": {
    "project_name": "",
    "project_desc": ""
  },
  "form2": {
    "property_one": "",
    "property_two": ""
  },
  "template_data": {
    "template_details": [
      {
        "Propertyone": "",
        "Propertytwo": "",
        "Propertythree": "",
        "Propertyfour": "",
        "Propertyfive": ""
      }
    ]
  }
}

预期输出:

{
  "form1": {
    "project_name": "",
    "project_desc": ""
  },
  "form2": {
    "property_one": "",
    "property_two": ""
  },
    "template_details" : [
    { "template_name": "Template One",
      "templateChild" : [{"property_one": "", "property_two":""}]
    },
    { "template_name": "Template Two",
      "templateChild" : [{"property_three": "", "property_four":"", 
                            "property_five":""}]
    }
    ]
}

如果我选择了多个选项(因为选择框是多选),则在template_properties内将形成以下内容。

表单分为三个部分,请不要在意第一和第二部分。选择框仅与第三部分有关。

请参考上面的预期输出以具有形式的JSON结构。如果我选​​择两个,则它不应替换值,它应在数组template_properties中获得多个对象。

{ "template_name": "Template One",
          "templateChild" : [{"property_one": "", "property_two":""}]
        },
        { "template_name": "Template Two",
          "templateChild" : [{"property_three": "", "property_four":"", 
                                "property_five":""}]
        }

千辛万苦,但我无法找到正确的解决方案。任何有角的人请使用demo来帮助我从当前输出中获得预期的输出。

1 个答案:

答案 0 :(得分:1)

只需创建“ Formula_details”作为具有FormGroup的FormArray,每个组具有“ tenplate_name” FormControl和“ template_child” FormArray。

为此替换动态表单组件:

import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, FormArray, FormControl, AbstractControl } from '@angular/forms';

import { QuestionBase } from './question-base';
import { QuestionControlService } from './question-control.service';

import { QuestionService } from './question.service';


@Component({
  selector: 'app-dynamic-form',
  templateUrl: './dynamic-form.component.html',
  providers: [QuestionControlService]
})
export class DynamicFormComponent implements OnInit {

  @Input() questions: QuestionBase<any>[] = [];
  @Input() questionsPartTwo: QuestionBase<any>[] = [];
  @Input() questionsPartThree: QuestionBase<any>[] = [];
  form: FormGroup;
  formPartTwo: FormGroup;
  formPartThree: FormGroup;
  formJoin: FormGroup;
  formJoin2: FormGroup;
  payLoad = '';
  allquestions: QuestionBase<any>[] = [];
  selectItems: any;

  jsonDataPart1: any = [
    {
      "elementType": "textbox",
      "class": "col-12 col-md-4 col-sm-12",
      "key": "project_name",
      "label": "Project Name",
      "type": "text",
      "value": "",
      "required": false,
      "minlength": 3,
      "maxlength": 20,
      "order": 1
    },
    {
      "elementType": "textbox",
      "class": "col-12 col-md-4 col-sm-12",
      "key": "project_desc",
      "label": "Project Description",
      "type": "text",
      "value": "",
      "required": true,
      "order": 2
    }
  ]

  jsonDataPart2: any = [
    {
      "elementType": "textbox",
      "class": "col-12 col-md-4 col-sm-12",
      "key": "property_one",
      "label": "Property One",
      "type": "text",
      "value": "",
      "required": true,
      "order": 3
    },
    {
      "elementType": "textbox",
      "class": "col-12 col-md-4 col-sm-12",
      "key": "property_two",
      "label": "Property Two",
      "type": "text",
      "value": "",
      "required": true,
      "order": 4
    }
  ]

  persons = [
    {
      key: 1, value: "Template one",
      personOneChild: [
        { property_name: "Property one" },
        { property_name: "Property two" }
      ]
    },
    {
      key: 2, value: "Template two",
      personTwoChild: [
        { property_name: "Property three" },
        { property_name: "Property four" },
        { property_name: "Property five" }
      ]
    },
    {
      key: 3, value: "Template three",
      personThreeChild: [
        { property_name: "Property six" },
        { property_name: "Property seven" }
      ]
    }
  ]

  array: any[] = [];

  constructor(private service: QuestionService, private qcs: QuestionControlService) { }
  ngOnInit() {
    this.questions = this.service.getQuestions(this.jsonDataPart1)
    this.form = this.qcs.toFormGroup(this.questions);

    this.questionsPartTwo = this.service.getQuestions(this.jsonDataPart2)

    this.formPartTwo = this.qcs.toFormGroup(this.questionsPartTwo);

    this.formJoin = new FormGroup({ form1: this.form, form2: this.formPartTwo });



  }
  changeEvent(e) {
    this.array = [];
    for (let select of this.selectItems) {
      let propertiesArray = [];

      this.array.forEach(element => {
        element.templateChild.forEach(data => {
          propertiesArray.push(
            {
              key: data.property_name.replace(' ',''),
              label: data.property_name,
              "elementType": "textbox",
              "type": "text"
            }
          )
        });
      });
      let values:any[]=propertiesArray.map(x=>x.key);
      let element=[{
        "elementType": "array",
        "key": "template_details",
        "value":values,
        "children":propertiesArray
      }]

      this.questionsPartThree = this.service.getQuestions(element);
            console.log(values);

      this.formPartThree = this.buildForm(+select) as AbstractControl;
      this.formJoin = new FormGroup({ form1: this.form, form2: this.formPartTwo, template_data: this.formPartThree });

    }
  }

  buildForm(selecteVal: number) {
    switch (selecteVal) {
        case 1:
          return new FormArray([
            new FormGroup({
              template_name: new FormControl("Template One"),
              template_child: new FormArray([
                new FormGroup({
                  property_one: new FormControl("property one"),
                  property_two: new FormControl("property two"),
                })
              ]),
            })
          ])
        case 2:
          return new FormArray([
            new FormGroup({
              template_name: new FormControl("Template One"),
              template_child: new FormArray([
                new FormGroup({
                  property_three: new FormControl("property three"),
                  property_four: new FormControl("property four"),
                })
              ]),
            })
          ])

          break;
        case 3:
return new FormArray([
            new FormGroup({
              template_name: new FormControl("Template One"),
              template_child: new FormArray([
                new FormGroup({
                  property_five: new FormControl("property five"),
                  property_six: new FormControl("property six"),
                })
              ]),
            })
          ])
          break;
      }
  }

  onSubmit() {
    this.payLoad = JSON.stringify(this.form.value);
  }

}


/*
Copyright 2017-2018 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/