使用angular2 RC2的模型驱动形式

时间:2016-06-17 21:34:27

标签: angular angular2-forms

更新到新的angular2 RC2后,我尝试按照我在网上找到的文档重新创建模型驱动表单,下面是代码

COMPONENT.ts

import { REACTIVE_FORM_DIRECTIVES, FormGroup, FormControl } from '@angular/forms';

myForm = new FormGroup({
  name: new FormGroup({
     first: new FormControl(),
     last: new FormControl()
  })
});

这是HTML代码

<form formGroup="myForm"  >
   <div formGroupName="name">
     <input formControlName ="first" >
     <input formControlName ="last" >
  </div>
</form>

但是在运行时,我收到了这个错误,

EXCEPTION: Error: Uncaught (in promise): Template parse errors:
No provider for NgControl ("
<form formGroup="myForm"  >
  <div formGroupName="name">
     [ERROR ->]<input formControlName ="first" >
     <input formControlName ="last" >
  </div>
"): ProductComponent@9:5

有没有人知道可能导致此错误的原因。

P.S新的模板驱动形式起作用,而不是模型驱动的 P.S我正在使用mgechev的Angular2-seed项目

2 个答案:

答案 0 :(得分:2)

更新到rc2后我遇到了同样的错误。在main.ts中,我改变了这一行 import csv import operator US = open('Test.csv', 'r')#Unsorted S = open('TestSorted.csv', 'w')#Sorted def sortinput(): option = input('Sort by name, gender or year?: ') if option == "name": choice = 0 elif option == "gender": choice = 1 elif option == "year": choice = 2 else: print('Invalid Input') csv1 = csv.reader(US, delimiter=',') sort = sorted(csv1, key=operator.itemgetter(choice)) for eachline in sort: print (eachline) with S as csvfile: fieldnames = ['Name', 'Gender', 'Year'] csv2 = csv.DictWriter(csvfile, fieldnames=fieldnames) csv2.writeheader() for eachline in sort: csv2.writerow({'Name': sort[0] ,'Gender': sort[1],'Year':sort[2][enter image description here][1]})

import { disableDeprecatedForms, provideForms } from '@angular/forms/index';

答案 1 :(得分:1)

以下内容可能有所帮助:

向packages.json文件中添加新表单。

"@angular/forms": "0.1.0",

禁用已弃用的表单并在主文件中启用新表单:

import {bootstrap} from '@angular/platform-browser-dynamic';
import {disableDeprecatedForms, provideForms} from '@angular/forms';

import {App} from './app';

bootstrap(App, [
    disableDeprecatedForms(),
    provideForms()
  ])
  .catch(err => console.error(err));

您的应用程序组件导入指令(FormControl,FormArray,FormGroup,REACTIVE_FORM_DIRECTIVES)来自新表单。请注意,ngFormModel现在是formGroup,ngControl现在是formControlName。

import {Component} from '@angular/core'
import { FormControl, FormArray, FormGroup, REACTIVE_FORM_DIRECTIVES, FormBuilder, Validators } from '@angular/forms';


@Component({
    selector: 'my-app',
    providers: [],
    template: `
        <div>
          <form [formGroup]="form">
                 <input [formControlName]="first">
                 <input [formControlName]="last">
          </form>
        </div>
      `,
    directives: [REACTIVE_FORM_DIRECTIVES]
})
export class App {
    public form: FormGroup;

    constructor(
        private fb: FormBuilder
    ) {

        this.form = fb.group({
            first: ["", Validators.required],
            last: ["", Validators.required]
        });
    }

}

我希望这会有所帮助。