angular2 cannot read property 'validator'

2019-09-01 02:24发布

I got some problem when use ngFormModel directive with form it said "TypeError: Cannot read property 'validator' of undefined in form_one (I write this code from NG-BOOK 2 Tutorial but it's not work!)

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);
  }
}

edited: (@Thierry Templier)

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

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

my libraries:

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

1条回答
ゆ 、 Hurt°
2楼-- · 2019-09-01 03:16

You need to define a form control in your component:

import {FormBuilder} from 'angular2/common';

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

You could have a look at this article for more details in the section "Using existing controls":

Edit

If you want to inject within ES6, you need to define a static getter parameter:

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]];
  }
}

Here is a working plunkr describing this approach: https://plnkr.co/edit/ymSUUCvG5NFvmCGqzj2r?p=preview.

See this question:

查看更多
登录 后发表回答