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

你离开我真会死。 提交于 2019-12-12 04:06:07

问题


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:


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":

  • Implementing Angular2 forms beyond basics - http://restlet.com/blog/2016/02/11/implementing-angular2-forms-beyond-basics-part-1/

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:

  • How to Inject Angular2 Http service into es6/7 Class?


来源:https://stackoverflow.com/questions/35556960/angular2-cannot-read-property-validator-of-undefined-when-use-ngformmodel-es6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!