0

我在使用带有表单的 ngFormModel 指令时遇到了一些问题,它说“TypeError: Cannot read property 'validator' of undefined in form_one (我从 NG-BOOK 2 Tutorial 编写了这段代码,但它不起作用!)

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'
4

1 回答 1

1

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

import {FormBuilder} from 'angular2/common';

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

您可以在“使用现有控件”部分查看本文以获取更多详细信息:

编辑

如果要在 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 。

看到这个问题:

于 2016-02-22T15:07:43.370 回答