FormArray usage and dynamically add row of controls

冷暖自知 提交于 2019-12-11 06:53:45

问题


I'm having trouble trying to do something with Angular 2 and Forms.
I have let's say an invitation list, where there are two fields, for name and e-mail, and a button to add more rows.

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

(+) Add row

And I kinda know that you can use FormArray to dynamically store different rows and so, but I'm not sure how to use it and to make it work.

So far at my component I have

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;
}

And I have this for my component 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>

回答1:


See the docs, 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}}


来源:https://stackoverflow.com/questions/51094563/formarray-usage-and-dynamically-add-row-of-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!