我正在使用Angular2的ReactiveFormsModule来创建包含表单的组件.这是我的代码:
foo.component.ts:
constructor(fb: FormBuilder) { this.myForm = fb.group({ 'fullname': ['',Validators.required],'gender': [] }); }
foo.component.html(带[formControl]):
<div class="fields"> <div class="field"> <label>Fullname*</label> <input type="text" [formControl]="myForm.controls.fullname"/> </div> </div> <div class="inline fields"> <label for="gender">Gender</label> <div class="field"> <div class="ui radio checkBox"> <input type="radio" name="gender" checked="" tabindex="0" class="hidden" [formControl]="myForm.controls.gender"> <label>Male</label> </div> </div> <div class="field"> <div class="ui radio checkBox"> <input type="radio" name="gender" tabindex="0" class="hidden" [formControl]="myForm.controls.gender"> <label>Female</label> </div> </div> </div>
foo.component.html(使用formControlName):
<div class="fields"> <div class="field"> <label>Fullname*</label> <input type="text" formControlName="fullname"/> </div> </div> <div class="inline fields"> <label for="gender">Gender</label> <div class="field"> <div class="ui radio checkBox"> <input type="radio" name="gender" checked="" tabindex="0" class="hidden" formControlName="gender"> <label>Male</label> </div> </div> <div class="field"> <div class="ui radio checkBox"> <input type="radio" name="gender" tabindex="0" class="hidden" formControlName="gender"> <label>Female</label> </div> </div> </div>
两种方式都有效.但我无法弄清楚使用[formControl]和formControlName之间的区别.
我相信你错过了一个重点:第二个例子中的[formGroup]指令. formControlName与[formGroup]一起使用以保存表单多点导航.例如:
<div> <input type="text" [formControl]="myForm.controls.firstName"/> <input type="text" [formControl]="myForm.controls.lastName"/> <input type="text" [formControl]="myForm.controls.email"/> <input type="text" [formControl]="myForm.controls.title"/> </div>
相当于:
<div [formGroup]="myForm"> <input type="text" formControlName="firstName"/> <input type="text" formControlName="lastName"/> <input type="text" formControlName="email"/> <input type="text" formControlName="title"/> </div>
现在想象一下嵌套的FormGroups 原文链接:https://www.f2er.com/angularjs/143908.html