【发布时间】:2019-09-21 09:57:22
【问题描述】:
我是 Angular 的新手。我正在尝试添加一个 formarray 以使用 formArray 动态显示表单控件。 我已经尝试了 angular.io 示例,它的工作原理如前所述,但我尝试向其中添加更多字段,但发现有些困难。
我的组件.ts
import { FormGroup, FormBuilder, Validators, FormArray } from '@angular/forms';
export class ReactiveFormsComponent implements OnInit {
public contactList: FormArray;
constructor(private fb: FormBuilder) { }
registrationForm = this.fb.group({
userName: ['',[Validators.required, Validators.minLength(3)]],
password:[''],
confirmPassword:[''],
address: this.fb.group({
city:[''],
state:[''],
postalCode:['']
}),
contacts: this.fb.array([this.createContact()])
});
createContact(): FormGroup {
return this.fb.group({
name: [],
email: []
});
}
// add a contact form group
addContact() {
this.contactList.push(this.createContact());
}
// remove contact from group
removeContact(index) {
this.contactList.removeAt(index);
}
registrationData = [];
onSubmit(){
console.log(this.registrationForm.value);
this.registrationData.push(this.registrationForm.value);
this.registrationForm.reset();
}
ngOnInit() {
this.contactList = this.registrationForm.get('contacts') as FormArray;
}
}
我的组件.html:
<div class="container-fluid mb-5">
<h2>Registration Form</h2>
{{ registrationForm.value | json }}
<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label>Username</label>
<input type="text" formControlName="userName" name="userName" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" formControlName="password" name="password" class="form-control">
</div>
<div formGroupName="address">
<div class="form-group">
<label>City</label>
<input type="text" formControlName="city" name="city" class="form-control">
</div>
---------
--------
</div>
<div formArrayName="contacts" *ngFor="let contacts of registrationForm.controls.contactList; let i = index;" >
<div [formGroupName]="i" >
<!-- Contacts Form controls Here -->
<input type="text" placeholder="name" formControlName="name">
<input type="text" placeholder="email" formControlName="email">
</div>
</div>
<button class="btn btn-primary" type="submit">Register</button>
奇怪的是,formArray 的 html 字段没有显示在模板中,而是显示了表单值。我使用“registrationForm.value | json”来显示表单值,如下所示
{ "userName": null, "password": null, "confirmPassword": null, "address": { "city": null, "state": null, "postalCode": null }, "contacts": [ { "name": null, "email": null } ] }
有人请用简单的例子解释一下吗?谢谢。
【问题讨论】:
-
您需要遍历
*ngFor="let contacts of registrationForm.get('contacts').controls;let i=index"或*ngFor="let contacts of contactList.controls;let i=index" -
谢谢兄弟,它对我有用@Eliseo
标签: angular angular-reactive-forms formarray