我正在将代码从 angular beta 迁移到 RC5 版本。我面临使用基于模型的表单的问题。因为我已经在 Angular 2 beta 中开发了很多形式。我很难将基于模型的表单更改为基于模板的表单。非常感谢表单迁移方面的任何帮助。
我现有的代码是这样的
个人资料.ts
import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} from '@angular/forms';
import {FormBuilder, FormGroup, FormControl, Validators} from '@angular/forms';
this.firstName = new FormControl();
this.lastName = new FormControl();
this.email = new FormControl();
this.addressLine = new FormControl();
this.postal = new FormControl();
this.postalArea = new FormControl();
this.form = builder.group({
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
addressLine: this.addressLine,
postal: this.postal,
postalArea: this.postalArea,
photo: this.photo
});
profile.HTML 中的模板如下
<form class="form-default" [formGroup]="form">
<input type="text" class="form-control" id="firstName" [(ngModel)]="model.firstName" formControlName="firstName" maxlength="200">
<input type="text" class="form-control" id="lastName" [(ngModel)]="model.lastName" formControlName="lastName" maxlength="200">
<input type="text" class="form-control" id="email" [(ngModel)]="model.username" readonly formControlName="email" maxlength="100">
</form>
我在控制台中面临以下错误。
异常:错误:未捕获(承诺):异常:/assets/scripts/my-profile/my-profile.html:176:66 中的错误原始异常:ngModel 不能用于使用父 formGroup 指令注册表单控件。尝试改用 formGroup 的合作伙伴指令“formControlName”。例子:
<div [formGroup]="myGroup"> <input formControlName="firstName"> </div> In your class: this.myGroup = new FormGroup({ firstName: new FormControl() }); Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions: Example: <div [formGroup]="myGroup"> <input formControlName="firstName"> <input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}"> </div>