根据用户操作创建表单。但不是一下子

Create forms according to the user action. But not at once

我必须像这样构建一个表单。

这预示着。即没有用户交互。

当用户按下 + 按钮时,它会像这样再次创建相同类型的 UI。

您可以看到用户可以一次又一次地添加任意数量的相同 UI 部分。你能告诉我怎么做吗?

我浏览了很多篇文章。但是它只创建了一次整个表单。即不像我的用例。有什么方向吗?

示例:https://jasonwatmore.com/post/2019/06/25/angular-8-dynamic-reactive-forms-example

https://alligator.io/angular/reactive-forms-formarray-dynamic-fields/

根据您需要复现的形式:

创建一个返回 formGroup 的函数来填充您的数组

createSchoolPath(): FormGroup {
  return this.fb.group({
    schoolName: '',
    level: '',
    topics: [],
    inProgress: true
})
}

然后您需要创建包含您的表单数组的父表单(并为您想要预先显示的第一个表单填充一次):

constructor( private fb: formBuilder) {}

form: FormGroup = this.fb.group({
  schoolPaths: this.fb.array([this.createSchoolPaths])
});

最后,当您想让用户添加更多部分时,您需要一种方法来填充您的数组:

/* component */

addSchoolPath(): void {
  const paths = this.form.get('schoolPaths') as FormArray;
  // use the first function to push a new formGroup
  paths.push(this.createSchoolPath());
}

<!-- html -->
<button (click)="addSchoolPath()">+</button>

显示它:

<form [formGroup]="form">
  <div formArrayName="schoolPaths" *ngFor="let path of form.get('schoolPaths').controls; let i = index">
    <div [formGroupName]="i">
      <!-- place your inputs here -->
    </div>
  </div>
</form>
<button (click)="addSchoolPath()">+</button>

为了补充 Gérôme 的回答,您也可以直接使用 formArray

createGroup()
{
   return new FormGroup({
      school:new FormControl(),
      level:new FormControl(),
      topic:new FormControl(),
      progress:new FormControl()
   })
}

首先你有一个formArray

formArray:FormArray=new FormArray([this.createGroup()])

添加按钮很简单

add()
{
   this.formArray.push(this.createGroup())
}

还有.html

<form [formGroup]="formArray">
   <div *ngFor="let group of formArray.controls" [formGroup]="group">
      <input formControlName="school">
      <input formControlName="level">
      <input formControlName="topic">
      <input formControlName="progress">
   </div>
</form>

看到,一般我们在 formGroup 中使用 formArray,但是如果你只想要一个 FormArray,你可以直接循环 formArray.controls