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

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

问题描述

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

 new TextboxQuestion({键:'名字',标签:'名字',价值: '',要求:真实,订单:1}),新的文本框问题({键:'姓氏',label: '姓氏',价值: '',要求:真实,订单:2}),

这两个字段需要首先加载.

此后我将有两个按钮作为添加和删除.

 

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

 new TextboxQuestion({键:'电子邮件地址',标签:'电子邮件',类型:'电子邮件',订单:3}),新的下拉问题({关键:'勇敢',标签:勇敢评级",选项: [{key: 'solid', value: 'solid'},{键:'伟大',价值:'伟大'},{键:'好',值:'好'},{键:'未经证实',价值:'未经证实'}],订单:4})

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

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

一次显示所有工作的stackblitz,https://stackblitz.com/edit/angular-x4a5b6

解决方案

使用 formArray 实现动态表单.

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

我将尝试解释如何扩展 https://angular.io/guide/dynamic-表单允许表单数组.

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

import { QuestionBase } from './question-base';导出类 ArrayQuestion 扩展 QuestionBase{controlType = '数组';类型:任何;构造函数(选项:{} = {}){超级(选项);}}

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

导出类 QuestionBase{值:T;...儿童:任何[];构造函数(选项:{价值?:T,...孩子?:有} = {}) {this.value = options.value;...this.children=options.children ||空值;}}

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

toFormGroup(questions: QuestionBase[]) {让组:任何= {};问题.forEach(问题=> {//如果控件类型是数组",我们创建一个FormArray如果(问题.控制类型==数组"){group[question.key]=new FormArray([]);}别的 {group[question.key] = question.required ?new FormControl(question.value || '', Validators.required): new FormControl(question.value || '');}});返回新的 FormGroup(group);}

好吧,我们将 dynamic-form.component 转换成一个 FormArray

<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>

</ng-容器><ng-container *ngIf="!question.children"><app-question [question]="question" [form]="form"></app-question></ng-容器>

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

 

还有两个函数 addControls 和 removeControls

 addControls(control: string) {让问题: any = this.questions.find(q => q.key == control);让孩子=问题?question.children : null;如果(儿童)(this.form.get(control) as FormArray).push(this.qcs.toFormGroup(children))}removeControls(控制:字符串){let array=this.form.get(control) as FormArray;array.removeAt(array.length-1);}

更新我忘了添加问题和示例:

让问题: QuestionBase[] = [新的文本框问题({键:'名字',标签:'名字',价值: '',要求:真实,订单:1}),新的文本框问题({键:'姓氏',label: '姓氏',价值: '',要求:真实,订单:2}),新数组问题({键:'myArray',价值: '',订单:3,孩子们: [新的文本框问题({键:'电子邮件地址',标签:'电子邮件',类型:'电子邮件',订单:3}),新的下拉问题({关键:'勇敢',标签:勇敢评级",选项: [{ key: 'solid', value: 'solid' },{ 键:'很棒',值:'很棒' },{ 键:'好',值:'好' },{ 键:'未经证实',值:'未经证实'}],订单:4})]})];

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.

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
  })

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.

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

解决方案

Implementing dynamic form with formArray.

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

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

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;
  }
}

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);
  }

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>

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>

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
          })
        ]
      })
    ];

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

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆