在 angular 中制作动态表单,在运行时添加字段

Making a dynamic form in angular, add fields on runtime

我正在制作一个网站,我可以在其中创建包含多项选择题的考试。我有一个 html 页面,我可以在其中向考试添加问题。

一个问题由问题的描述和多个选项组成。选项包含响应和用于检查响应是真还是假的值。

用户应该能够在填写表格时向问题添加选项。我正在尝试为此使用 formbuilder、formgroup 和 formarray,但它不起作用。当我按下添加选项时,应该会出现一个新的响应和一个新的有效字段。

这些字段出现在我的 html 页面上,但我在填写表格时遇到此错误。 "Cannot find control with name response"+"cannot find control with name valid"

这是 HTML 页面:

    <form [formGroup]="questionForm" (ngSubmit)="onSubmit(questionForm.value)">
        <div>
          <label>Description:</label>
          <br />
          <input class="form-control" id="description" type="text" formControlName="description">
          <br />
          <label>Options</label>

          <div *ngFor="let test of arrayOptions; let i = index">
            <div class=mx-4>
              <label>Response</label>
              <input class="form-control" id="response" type="text" formControlName="response">
              <label>Valid</label>
              <input class="form-control" id="valid" type="text" formControlName="valid">
            </div>


          </div>

          <button type="button" class="btn-block-option text-primary" (click)="addOption()">
            <i class="fa fa-plus" aria-hidden="true"></i>Add option
          </button>


        </div>
        <div class="block-content block-content-full block-content-sm bg-body-light font-size-sm">
          <button class="btn btn-primary" type="submit">Add</button>
        </div>
      </form>

这是我的 ts 页面:

    export class AddQuestionComponent implements OnInit {

      questionForm;
      arrayOptions;

      constructor(
        private examSimulatorService: ExamSimulatorService,
        private formBuilder: FormBuilder
      ) {
        this.questionForm = this.formBuilder.group({
          description: '',
          options: ''
        })
      }
      removeOption(i) {
        this.questionForm.removeControl(i);
      }
      addOption() {

    this.questionForm.addControl(this.questionForm.controls.options.value, 
    this.formBuilder.array([this.formBuilder.group(
          {
            response: "",
            valid: ""
          }
        )]));
        this.arrayOptions.push(this.questionForm.controls.options.value);
      } 

      onSubmit(questionData) {
        this.examSimulatorService.addQuestion(questionData);
        this.questionForm.reset();
      }

      ngOnInit() {
        this.arrayOptions = [];
        this.addOption();
      }

    }

您没有在 html

中添加 formArray 和 formGroup

HTML代码:

<form [formGroup]="questionForm" (ngSubmit)="onSubmit(questionForm.value)">
<div>
   <label>Description:</label>
   <br />
   <input class="form-control" id="description" type="text" formControlName="description">
   <br />
   <label>Options</label>
   <div formArrayName="options">
      <div *ngFor="let test of arrayOptions; let i = index">
         <div class=mx-4 [formGroupName]="i">
            <label>Response</label>
            <input class="form-control" id="response" type="text" formControlName="response">
            <label>Valid</label>
            <input class="form-control" id="valid" type="text" formControlName="valid">
         </div>
      </div>
   </div>
   <button type="button" class="btn-block-option text-primary" (click)="addOption()">
   <i class="fa fa-plus" aria-hidden="true"></i>Add option
   </button>
</div>
<div class="block-content block-content-full block-content-sm bg-body-light font-size-sm">
   <button class="btn btn-primary" type="submit">Add</button>
</div>
</form>

组件:

export class AppComponent implements OnInit {
  questionForm;
  arrayOptions;
  constructor(private formBuilder: FormBuilder) {
    this.questionForm = this.formBuilder.group({
      description: "",
      options: this.formBuilder.array([])
    });
  }

  ngOnInit() {
    this.arrayOptions = [];
    this.addOption();
  }

  removeOption(i) {
    this.questionForm.removeControl(i);
  }

  addOption() {
    const control = <FormArray>this.questionForm.get("options");
    const newGroup = this.formBuilder.group({
      response: "",
      valid: ""
    });
    control.push(newGroup);
    this.arrayOptions.push(this.questionForm.controls.options.value);
  }

  onSubmit(questionData) {
    console.log(questionData);
  }
}

Find the code here

如果没有 运行 样本,很难说出确切的错误。

我注意到的一些事情:

1) 当我们使用 FormArray 时,我们必须通过 formArrayName

在模板中绑定它

2) 我真的不明白你为什么要在 questionForm 上调用 addControl。我们不应该向 FormArray 推送一个新选项吗?

带有 FormArray 的示例表单:

this.questionForm = this.fb.group({
  question: ["Sample Question"],
  options: this.fb.array([
    this.fb.group({
      response: ["Response Example"],
      valid: [true]
    })
  ])
});

通过 formArrayName 引用模板中的 FormArray:

<form [formGroup]="questionForm">
  <input type="text" formControlName="question" />

  <div formArrayName="options">

    <div *ngFor="let option of options.controls; let i=index">
      <b>Option {{i}}:</b>
      <div [formGroupName]="i">
          <input type="text" formControlName="response" />
          <input type="checkbox" formControlName="valid" />
      </div>
    </div>

</div>
</form>

最后是添加新选项的方法:

addOption() {
  this.options.push(
    this.fb.group({
      response: [""],
      valid: [false]
    })
  );
}

// getter which simplifies the access via 'this.options' used in the addOption method
get options() {
  return this.myForm.get("options") as FormArray;
}

看看codesandbox。请随意分叉和编辑它,以便它更好地显示您的问题。