角动态表单嵌套字段 [英] Angular dynamic form nested fields

查看:74
本文介绍了角动态表单嵌套字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

借助 https://angular.io/guide/dynamic-form ,我正在制作一个动态表格,首先需要显示两个字段.

With the help of https://angular.io/guide/dynamic-form, i am making a dynamic form where i am in the need to display two fields at first.

  new TextboxQuestion({
    key: 'firstName',
    label: 'First name',
    value: '',
    required: true,
    order: 1
  }),

  new TextboxQuestion({
    key: 'lastName',
    label: 'Last name',
    value: '',
    required: true,
    order: 2
  }),

这两个字段必须在加载时首先显示.

These two fields needs to be at first on loading.

此后,我将有两个按钮为add and remove.

After this i will have two buttons as add and remove.

  <button (click)="addNew()"> Add </button> &nbsp;&nbsp;&nbsp;
  <button (click)="removeNew()"> Remove </button> <br><br>

通过单击添加,我需要显示接下来的两个字段(以下字段)

By clicking add, i need to display the next two fields (the following fields),

  new TextboxQuestion({
    key: 'emailAddress',
    label: 'Email',
    type: 'email',
    order: 3
  }),

  new DropdownQuestion({
    key: 'brave',
    label: 'Bravery Rating',
    options: [
      {key: 'solid',  value: 'Solid'},
      {key: 'great',  value: 'Great'},
      {key: 'good',   value: 'Good'},
      {key: 'unproven', value: 'Unproven'}
    ],
    order: 4
  })

订单1& 2处于初始状态,然后点击添加下两个订单3&需要显示4个.

Order 1 & 2 in the initial state and after clicking add the next two order 3 & 4 needs to get displayed.

请帮助我实现单击添加"按钮时添加子字段的结果.

KIndly help me to achieve the result of adding child fields on click add button.

一次显示所有内容的工作堆栈闪电战, https://stackblitz.com/edit/angular- x4a5b6

The working stackblitz which displays all at once, https://stackblitz.com/edit/angular-x4a5b6

推荐答案

使用formArray实现动态表单.

Implementing dynamic form with formArray.

嗯,事情更复杂了.我做了一个stackblik,请参见 demo

Well, the things are more complex. I make a stackblik, see demo

我将尝试说明如何扩展 https://angular.io/guide/dynamic-表格以允许使用表格数组".

I'll try to explain how extends the https://angular.io/guide/dynamic-form to allow Form Array.

我们首先需要做的是创建一种新型的问题,一个questionArray

The first we need make is create a new type of question, a questionArray

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

export class ArrayQuestion extends QuestionBase<string> {
  controlType = 'array';
  type: any;

  constructor(options: {} = {}) {
    super(options);
  }
}

我们必须更改问题库以添加新的属性儿童"

We must change question base to add a new property "children"

export class QuestionBase<T> {
  value: T;
  ...
  children:any[];

  constructor(options: {
      value?: T,
      ...
      children?:any
    } = {}) {
    this.value = options.value;
    ...
    this.children=options.children || null;
  }
}

添加更改问题控制服务以允许管理formArrays

Add change the question-control service to allow manage formArrays

toFormGroup(questions: QuestionBase<any>[]) {
    let group: any = {};

    questions.forEach(question => {
      //If the control type is "array" we create a FormArray
      if (question.controlType=="array") {
         group[question.key]=new FormArray([]);
      }
      else {
        group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)
          : new FormControl(question.value || '');
      }
    });
    return new FormGroup(group);
  }

好吧,我们将dynamic-form.component转换为显示FormArray

Well We transform the dynamic-form.component to show a FormArray

<div *ngFor="let question of questions" class="form-row">
    <ng-container *ngIf="question.children">
        <div [formArrayName]="question.key">
            <div *ngFor="let item of form.get(question.key).controls; let i=index" [formGroupName]="i">
                <div *ngFor="let item of question.children">
                    <app-question [question]="item" [form]="form.get(question.key).at(i)"></app-question>
                </div>
            </div>
        </div>
    </ng-container>
    <ng-container *ngIf="!question.children">
        <app-question [question]="question" [form]="form"></app-question>

    </ng-container>
</div>

就这样.那么,如何增加和减少formArrays?我们有两个按钮

And just it doit. Well, how increment and decrement the formArrays? We have two buttons

  <button (click)="addControls('myArray')"> Add </button>
  <button (click)="removeControls('myArray')"> Remove </button> <br><br>

和两个函数addControls和removeControls

And two functions addControls and removeControls

  addControls(control: string) {
    let question: any = this.questions.find(q => q.key == control);
    let children = question ? question.children : null;
    if (children)
      (this.form.get(control) as FormArray).push(this.qcs.toFormGroup(children))
  }
  removeControls(control: string){
    let array=this.form.get(control) as FormArray;
    array.removeAt(array.length-1);
  }

更新,我忘记添加问题的示例了:

Update I forgot add and example of questions:

let questions: QuestionBase<any>[] = [

      new TextboxQuestion({
        key: 'firstName',
        label: 'First name',
        value: '',
        required: true,
        order: 1
      }),

      new TextboxQuestion({
        key: 'lastName',
        label: 'Last name',
        value: '',
        required: true,
        order: 2
      }),
      new ArrayQuestion({
        key: 'myArray',
        value: '',
        order: 3,
        children: [
          new TextboxQuestion({
            key: 'emailAddress',
            label: 'Email',
            type: 'email',
            order: 3
          }),
          new DropdownQuestion({
            key: 'brave',
            label: 'Bravery Rating',
            options: [
              { key: 'solid', value: 'Solid' },
              { key: 'great', value: 'Great' },
              { key: 'good', value: 'Good' },
              { key: 'unproven', value: 'Unproven' }
            ],
            order: 4
          })
        ]
      })
    ];

这篇关于角动态表单嵌套字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆