FormArray的使用和动态添加一行控件

FormArray usage and dynamically add row of controls

我在尝试使用 Angular 2 和 Forms 时遇到问题。
我假设有一个邀请列表,其中有两个字段,用于姓名和电子邮件,以及一个用于添加更多行的按钮。

|__name_______|__e-mail_______|
|__name_______|__e-mail_______|

(+) 添加行

我知道您可以使用 FormArray 来动态存储不同的行等,但我不确定如何使用它以及如何让它发挥作用。

到目前为止我的组件

form:FormGroup;
ngOnInit() {
    this.form = new FormGroup({
      invitee: new FormArray([])
    });
    this.addInvitee();
}

addInvitee() {
    let control = <FormArray>this.form.controls['invitee'];
    control.push(new FormGroup({
      name: new FormControl('', Validators.required),
      email: new FormControl('', Validators.required)
    }));
}

get inviteeArrayControl(): AbstractControl[] {
    let control = this.form.controls['invitee'] as FormArray;
    return control.controls;
}

我的组件有这个 HTML

<div *ngFor="let discounts of discountsArrayControl;let i = index">
    <div [formGroupName]="i">
        <!-- Here goes the inputs but I don't know how to use them -->
    </div>
</div>
<button (click)="addInvitee()">(+) Add row</button>

查看文档,https://angular.io/guide/reactive-forms#use-formarray-to-present-an-array-of-formgroups

<form [formGroup]="form" (submit)="submit(form)"> <!-- your form-->
    <!--if your form has fields that they are not array, put here
    <input formControlName="field_in_not_array">
    -->
    <div formArrayName="invitee"> <!-- the Form Array of your form-->
        <!-- a *ngFor over form.get('invitee').controls -->
        <div *ngFor="let address of form.get('invitee').controls; let i=index" 
                [formGroupName]="i" >
           <!--here the fields of the array-->
           <input formControlName="name"/> 
           <input formControlName="email"/>
        </div>
     </div>
</form>
<button (click)="addInvitee()">(+) Add row</button>
<!--only to check-->
{{form?.value |json}}