FormBuilder给出了控制台错误

时间:2017-04-05 11:54:32

标签: angular

我正在尝试为表单using this article添加验证。 当我使用带有FormBuilder的构造函数时,会抛出错误,说EXCEPTION: Uncaught (in promise): Error: DI Error

test1.component.ts

import { Component, Inject, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { FormComponent } from '../form/form.component';

@Component({
  selector: 'app-test1',
  templateUrl: './test1.component.html',
  styleUrls: ['./test1.component.css']
})
export class Test1Component extends FormComponent {
  complexForm : FormGroup;

  constructor(@Inject(FormBuilder) fb: FormBuilder){
    super();
    this.complexForm = fb.group({
        'firstName' : "",
        'lastName': "",
        'gender' : "Female",
        'hiking' : false,
        'running' : false,
        'swimming' : false
    });
  }

  saveForm(){
    console.log("Child Form save");
    return true;
  }
}

以下是控制台错误 enter image description here

我该如何解决这个问题?

我试图提出一个plunker with an example from angular docs,但它发出了一些其他错误,

修改1:

根据AJT_82的建议,我将构造函数更改为constructor(private fb: FormBuilder){。但它现在给了我另一个错误

enter image description here

1 个答案:

答案 0 :(得分:2)

更改您在构造函数中注入FormBuilder的方式:

constructor(@Inject(FormBuilder) fb: FormBuilder)

简单地说:

constructor(private fb: FormBuilder)

至于第二个错误,建议您确保在app-module中同时包含FormsModuleReactiveFormsModule

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    FormsModule,
    ReactiveFormsModule,
  ]
  ....
})