Angular 2提交动态表单

时间:2017-06-06 09:24:30

标签: angular

我的数据库有Questions,每个问题都有1-N questionTypes,而questionType的问题可能有0-N answers

enter image description here

我正在尝试使用Angular 2来实现一个像plnkr这样的表单,我可以使用add button插入尽可能多的答案(标签+值),然后保存单个类型的答案save button

问题在于我不知道如何完成它,¿任何帮助?

1 个答案:

答案 0 :(得分:1)

如果要在表单中使用数组,则必须使用FormBuilder

import {FormArray, FormBuilder, FormGroup} from '@angular/forms';

constructor(private fb: FormBuilder} {}

public questionsForm: FormGroup = this.fb.group({
  questions: this.fb.array([])
});

addInfo(label: string, value: string): void {

  const questions: FormArray = <FormArray>this.questionsForm.get('questions');

  questions.push(this.fb.group({label: label, value: value}));

  this.label = '';
  this.value = '';
}

saveQuestion(): void {

  // This will give you {questions: [{label: '', value: ''}, ...]}
  const formValue = this.questionsForm.value;
}

然后是模板:

<form [formGroup]="questionsForm" (ngSubmit)="saveQuestion()" novalidate>
  <div *ngFor="let info of questionForm.get('questions').controls" [formGroup]="info">
    <input formControlName="label>
    <input formControlName="value">
  </div>

  <input [(ngModel]="label" [ngModelOptions]="{standalone: true}" type="text" placeholder="label">
  <input [(ngModel]="value" [ngModelOptions]="{standalone: true}" type="text" placeholder="value">

  <button (click)="addInfo(label, value)">Add</button>

  <p>
    <button type="submit">Save Question</button>
  </p>
</form>