Javascript FormArray用法并动态添加控件行
我在尝试使用Angular 2和Forms进行某些操作时遇到困难。Javascript FormArray用法并动态添加控件行,javascript,angular,angular2-forms,Javascript,Angular,Angular2 Forms,我在尝试使用Angular 2和Forms进行某些操作时遇到困难。 比如说,我有一个邀请列表,其中有两个字段,分别是“姓名”和“电子邮件”,还有一个添加更多行的按钮。 |__姓名uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu124; |__姓名/电子邮件_______| (+)添加行 我知道可以使用FormArray动态存储不同的行,但我不知道如何使用它,如何使它工作 到目前为止,我的组件 form:FormGroup; ngOnInit() {
比如说,我有一个邀请列表,其中有两个字段,分别是“姓名”和“电子邮件”,还有一个添加更多行的按钮。
|__姓名uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu124;
|__姓名/电子邮件_______| (+)添加行 我知道可以使用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;
}
形式:FormGroup;
恩戈尼尼特(){
this.form=new FormGroup({
受邀方:新形式([])
});
这是addinvite();
}
addInvitee(){
让control=this.form.controls['invitee'];
控件。推送(新窗体组)({
名称:新FormControl(“”,需要验证程序),
电子邮件:新FormControl(“”,验证器。必填)
}));
}
get-InviteArrayControl():AbstractControl[]{
让control=this.form.controls['invitee']作为FormArray;
返回控制。返回控制;
}
我把它作为我的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>
(+)添加行
参见文档
(+)添加行
{{form?.value | json}}
<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}}