javascript - FormArray 的用法和动态添加一行控件
问题描述
我在尝试使用 Angular 2 和 Forms 做某事时遇到了麻烦。
我有一个邀请列表,其中有两个字段,名称和电子邮件,以及一个添加更多行的按钮。
|__姓名________|__电子邮件_______|
|__姓名________|__电子邮件_______|
(+) 添加行
而且我知道您可以使用 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}}
推荐阅读
- excel - 将字符串更改为具有精确字符串的变量时,VBA 会引发错误
- android - 广告关闭时如何启动第二个活动?(科特林)
- c++ - 如何使用变量值来提供空间
- python - 如何在 PyGad 中将 ga_instance 加载为“.pkl”格式?
- r - 为特定 Geom_point 插入图例
- macos - Docker 无法启动,无法注册 vmnetd:操作无法完成。(CFErrorDomainLaunchd 错误 4。)
- python - 为什么深度 Q 学习不能有效工作?
- pandas - Pandas Sequebtial 组内成员的计数和总和
- python - 获取生成器生成特定项目的最小执行次数
- c++ - 将 Winsock2 添加到我的 MinGW-w64 C/C++ 会导致:未定义对“InitializeConditionVariable”的引用