使用 ngFormModel (ES6) 时,angular2 无法读取未定义的 属性 'validator'

angular2 cannot read property 'validator' of undefined when use ngFormModel (ES6)

我在将 ngFormModel 指令与表单一起使用时遇到了一些问题 它说“类型错误:无法读取 form_one 中未定义的 属性 'validator'(我从 NG-BOOK 2 教程中编写这段代码,但它不起作用!)

import {Component} from 'angular2/core'
import {
  FORM_DIRECTIVES,
  FormBuilder,
  ControlGroup,
  Validators
} from 'angular2/common'

@Component({
  selector: 'demo-form-sku-builder',
  directives: [FORM_DIRECTIVES],
  template: `
  <div class="ui raised segment">
    <h2 class="ui header">Demo Form: Sku with FormBuilder</h2>
    <form class="ui form"
      [ngFormModel]="myForm"
      (ngSubmit)="onSubmit(myForm.value)">
      <div class="field">
        <label for="skuInput">SKU</label>
        <input type="text"
          id="skuInput"
          placeholder="SKU"
          [ngFormControl]="myForm.controls['sku']">
      </div>

      <button type="submit" class="ui button">Submit</button>
    </form>
  </div>
  `
})
export class DemoFormSkuBuilder {

  contructor (formBuilder) {
      this.myForm = formBuilder.group({
        'sku': ['', Validators.required]
      })
  }

  onSubmit(value) {
    console.log("you submitted value: ", value);
  }
}

编辑:(@Thierry Templier)

contructor (formBuilder) {
    this.fb = formBuilder;
    this.myForm = this.fb.group({
      'sku': ['', Validators.required]
    })
  }

  static get parameters() {
    return [[FormBuilder]];
  }

我的图书馆:

import 'es6-shim';
import 'reflect-metadata';
import 'zone.js/dist/zone-microtask'
import 'rxjs/Rx'
import 'es6-promise'

您需要在您的组件中定义一个表单控件:

import {FormBuilder} from 'angular2/common';

@Component({
  (...)
})
export class DemoFormSkuBuilder {
  contructor (private fb:FormBuilder) {
    this.form_one = this.fb.group({
      (...)
    });
  }
}

您可以在 "Using existing controls":

部分查看这篇文章以获取更多详细信息

编辑

如果要在ES6内注入,需要定义静态getter参数:

import {FormBuilder} from 'angular2/common';

@Component({
  (...)
})
export class DemoFormSkuBuilder {
  contructor (fb) {
    this.fb = fb;
    this.form_one = this.fb.group({
      (...)
    });
  }

  static get parameters() {
    return [[FormBuilder]];
  }
}

这是一个描述这种方法的工作 plunkr:https://plnkr.co/edit/ymSUUCvG5NFvmCGqzj2r?p=preview

看到这个问题: