Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了含有列表的Angular2反应形式大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试为用户创建一个表单,允许用户将电话号码与用户关联.目前实施的反应形式是否可行?例如,我希望下面的表单可以接受许多电话号码.我的前端实现将显示电话号码字段,并且将具有允许添加额外电话号码字段的按钮.
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()
});

我可以抑制其他电话字段,直到单击添加其他电话号码按钮.

@H_616_9@
@H_616_9@
您想要使用的是 @L_801_10@,您可以在其中动态添加新的表单控件:
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>

Demo

@H_616_9@

大佬总结

以上是大佬教程为你收集整理的含有列表的Angular2反应形式全部内容,希望文章能够帮你解决含有列表的Angular2反应形式所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。