没有FormBuilder的提供者

时间:2016-10-25 20:24:09

标签: angular

我还是新手并通过教程学习,但由于某种原因,我在尝试测试唯一用户名时收到了消息No provider for formbuilder。 我不确定为什么我会收到此消息,但我无法找到解决方案。谁能告诉我为什么会这样?

注册-component.ts

import {Component} from '@angular/core';
import {ControlGroup, Control, Validators, FormBuilder} from '@angular/common'
import {UsernameValidators} from './usernameValidators'

@Component({
selector: 'signup',
templateUrl: 'signup-component.html'

})
export class SignupComponent{
  form: ControlGroup;

  constructor(fb: FormBuilder){
    this.form = fb.group({
      username:['', Validators.compose([
          Validators.required, UsernameValidators.cannotContainSpace
      ])],
      password: ['', Validators.required]
    })
  }
}

usernameValidators.ts

import {Control} from '@angular/common'


export class UsernameValidators{

  static shouldBeUnique(control: Control){
    return new Promise((resolve, reject) => {
      setTimeout(function(){
        if(control.value == "andy")
          resolve({shouldBeUnique: true});
        else
          resolve(null);
      }, 1000);

    });

  }


  static cannotContainSpace(control: Control){
    if (control.value.indexOf(' ') >= 0)
      return {cannotContainSpace: true};

    return null;
  }
}

1 个答案:

答案 0 :(得分:71)

导入ReactiveFormsModuleFormsModule

@NgModule({
  imports: [
      BrowserModule /* or CommonModule */, 
      FormsModule, ReactiveFormsModule
  ],
  ...
})

在您使用FormBuilder

的模块中