Angular 动态表单嵌套字段

2024-03-23

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

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

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

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

之后我将有两个按钮add and remove.

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

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

  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。

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

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


使用 formArray 实现动态表单。

嗯,事情更复杂。我做了一个 stackblik,看demo https://stackblitz.com/edit/angular-x4a5b6-xcychx?file=src%2Fapp%2Fdynamic-form.component.html

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

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

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

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

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

我们必须更改问题库以添加新属性“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

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

<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 呢?我们有两个按钮

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

还有两个函数addControls和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我忘记添加问题和示例:

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
          })
        ]
      })
    ];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 动态表单嵌套字段 的相关文章

随机推荐