如何创建 Angular 6 反应式表单,其中使用按钮添加和删除表单组

How to create an Angular 6 reactive form where form groups are added and removed with buttons

我正在尝试创建一个 Angular 6 响应式表单,用于构建 json 以提交给 REST API。 结构是这样的:

audioTrack:
  path: /foo.mp4
  track: 1
  actions:
    normalize: {}
    addNoise:
      level: 5
subtitleTracks:
- path: /foo.en.srt
  format: SubRip
  actions:
    convert:
      format: WebVTT
- path: /foo.es.vtt
  format: WebVTT
  actions:
    spellCheck: {}

所以只有一个音轨和一个字幕轨列表 这些轨道中的任何一个都是可选的。 我想将每个轨道封装为一个组件,该组件具有一个表单组,该表单组是单个表单的一部分。使用按钮添加或删除曲目。

我没能找到任何这样做的例子。我找到了专注于添加和删除单个控件的内容,而不是整个表单组。

我认为这将是一个典型的用例,我错过了什么?

如果我构建一个静态表单,那么一切正常,但是向父组件添加和删除组件的简单操作很快就会变得一团糟,我只是不知道如何继续。

我认为您缺少的是 FormArray。 angular.io 中有一个教程与您的问题类似,如果我理解正确的话:

https://angular.io/guide/reactive-forms 搜索表单 FormArray

https://stackblitz.com/angular/gdygpengbdl 这里是教程的代码和 运行 应用程序,选择 FormArray 演示。在此演示中,您可以为英雄添加地址,类似于您想要实现的目标。

您需要使用 Form Array. This allows you (if you are not familiar with this) to store an array of form groups that can be pushed or popped from the array stack. An example of this can be seen here。我会解释发生了什么。

  • (1) 通过表单生成器或手动创建表单数组,具体取决于 您的偏好
  • (2) 使用标准 JavaScript 数组 push method
  • 将组推入数组
  • (3) 使用表单数组 class 上的 removeAt 函数从数组中删除组。

注意您需要使用 ngFor 来遍历表单数组中的表单组。这使您可以直观地看到在浏览器中添加或删除的动态创建的表单组。

这看起来像这样:

<div *ngFor="let track of audioTracks.controls; let i=index" [formGroupName]="i"> Your custom html here... <div>