我正在尝试为用户创建一个表单,允许用户可以将电话号码与用户关联。目前实施的反应形式是否可行?例如,我希望下面的表单可以接受许多电话号码。我的前端实现将显示电话号码字段,并且将有一个按钮,允许添加额外的电话号码字段。
userForm = new FormGroup({
firstName: new FormControl('', Validators.required),
lastName: new FormControl('', Validators.required),
phoneNumber: new FormControl('', Validators.required)
});
我的黑客解决方案是
userForm = new FormGroup({
firstName: new FormControl('', Validators.required),
lastName: new FormControl('', Validators.required),
phoneNumber: new FormControl('', Validators.required),
phoneNumber1: new FormControl(),
phoneNumber2: new FormControl(),
phoneNumber3: new FormControl(),
phoneNumber4: new FormControl()
});
我可以取消附加的手机字段,直到点击添加额外的电话号码按钮。
答案 0 :(得分:12)
您想要使用的是FormArray
,您可以在其中动态添加新的表单控件:
constructor(private fb: FormBuilder) { }
// build form
this.userForm = this.fb.group({
numbers: this.fb.array([
new FormControl()
])
});
// push new form control when user clicks add button
addNumber() {
const control = <FormArray>this.userForm.controls['numbers'];
control.push(new FormControl())
}
然后是你的模板:
<form [formGroup]="userForm" (ngSubmit)="submit(userForm.value)">
<div formArrayName="numbers">
<!-- iterate the array of phone numbers -->
<div *ngFor="let number of userForm.controls.numbers.controls; let i = index" >
<label>PhoneNumber {{i+1}} </label>
<input formControlName="{{i}}" />
</div>
</div>
<button type="submit">Submit</button>
</form>