angular - angular2 cannot read property 'validator' of undefined when use ngFormModel (ES6) -
i got problem when use ngformmodel directive form said "typeerror: cannot read property 'validator' of undefined in form_one (i write code ng-book 2 tutorial it's not work!)
import {component} 'angular2/core' import { form_directives, formbuilder, controlgroup, validators } 'angular2/common' @component({ selector: 'demo-form-sku-builder', directives: [form_directives], template: ` <div class="ui raised segment"> <h2 class="ui header">demo form: sku 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 parameters() { return [[formbuilder]]; }
my libraries:
import 'es6-shim'; import 'reflect-metadata'; import 'zone.js/dist/zone-microtask' import 'rxjs/rx' import 'es6-promise'
you need define form control in component:
import {formbuilder} 'angular2/common'; @component({ (...) }) export class demoformskubuilder { contructor (private fb:formbuilder) { this.form_one = this.fb.group({ (...) }); } }
you have @ article more details in 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 want inject within es6, need define static getter parameter:
import {formbuilder} 'angular2/common'; @component({ (...) }) export class demoformskubuilder { contructor (fb) { this.fb = fb; this.form_one = this.fb.group({ (...) }); } static parameters() { return [[formbuilder]]; } }
here working plunkr describing approach: https://plnkr.co/edit/ymsuucvg5nfvmcgqzj2r?p=preview.
see question:
Comments
Post a Comment