Angular2模型驱动的形式和预先填充的值

时间:2016-06-29 18:13:33

标签: angular angular2-forms

我有一个我为rc.1构建的应用程序,我现在正在升级到rc.3,以及新的表单模块。我一直在扯掉我的头发,并决定看看是否有人有任何想法我做错了。

基本上我构建这样的表单(fb是FormBuilder的一个实例):

this.form = fb.group({
  client_id: ['Customer', Validators.compose([Validators.required, formValidators.mustBeNumber])],
  data_owner_id: ['Data Owner (if different from Customer)', formValidators.mustBeNumber],
  order_time: [new Date(), Validators.compose([formValidators.mustBeDate, Validators.required])]
})

使用ngModel进行预填充:

<form class="form"  [formGroup]="form" (ngSubmit)="submitJob(f)">
      <legend>{{title}}</legend>
      <div class="form-group">
        <label for="client_id">Client</label>
   <select (change)="clientHasChanged($event.target.value)" class="form-control" id="client_id" formControlName="client_id" [(ngModel)]='job.client_id'>
              <option value="" disabled selected>Customer</option>
              <option *ngFor="let client of clients" [ngValue]="client.client_id">{{client.client_id}} - {{client.client_id_name}}</option>
            </select>

这对于rc.1(在重命名的指令之外)完全正常,但现在我收到错误:

  

browser_adapter.ts:74 EXCEPTION:http://localhost:4200/app/+wih2/+job/job.component.html:6:129出错   原始例外:&#39;&#39;

没有值访问者

删除ngModel会删除错误,但我需要它提供的数据,而且我不知道有任何其他解决方法。

我正在使用新的表单模块,是的,我正在使用它:

bootstrap(AppComponent, [disableDeprecatedForms(), provideForms(), HTTP_PROVIDERS, APP_ROUTER_PROVIDERS]);

期待一些答案!

编辑: 完整的堆栈跟踪stacktrace

2 个答案:

答案 0 :(得分:1)

我认为更好的解决方案是使用Reactive solution。

在你的ngOnInit()

中有类似的东西
this.form.controls["client_id"].valueChanges.subscribe(value => {
    this.job.client_id = value;
});

在模板中使用属性绑定

答案 1 :(得分:0)

问题是我从@ angular / common导入NgModel,而不是@ angular / forms - 我不知道NgModel与表单紧密耦合。