我正在尝试为用户创建一个表单,允许用户将电话号码与用户关联.目前实施的反应形式是否可行?例如,我希望下面的表单可以接受许多电话号码.我的前端实现将显示电话号码字段,并且将具有允许添加额外电话号码字段的按钮.
userForm = new FormGroup({ firstName: new FormControl('',Validators.required),lastName: new FormControl('',phoneNumber: new FormControl('',Validators.required) });
我的黑客解决方案是
userForm = new FormGroup({ firstName: new FormControl('',phoneNumber1: new FormControl(),phoneNumber2: new FormControl(),phoneNumber3: new FormControl(),phoneNumber4: new FormControl() });
我可以抑制其他电话字段,直到单击添加其他电话号码按钮.
您想要使用的是
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>