这种情况

我试图在我的Angular应用程序中创建一个非常简单的表单,但无论如何,它都无法工作。

Angular版本

Angular 2.0.0 RC5

这个错误

不能绑定到'formGroup'因为它不是'form'的已知属性

的代码

视图

<form [formGroup]="newTaskForm" (submit)="createNewTask()">
   <div class="form-group">
      <label for="name">Name</label>
      <input type="text" name="name" required>
   </div>
   <button type="submit" class="btn btn-default">Submit</button>
</form>

控制器

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder }  from '@angular/forms';
import {FormsModule,ReactiveFormsModule} from '@angular/forms';
import { Task } from './task';

@Component({
    selector: 'task-add',
    templateUrl: 'app/task-add.component.html'

})
export class TaskAddComponent {

    newTaskForm: FormGroup;

    constructor(fb: FormBuilder)
    {
        this.newTaskForm = fb.group({
            name: ["", Validators.required]
        });
    }

    createNewTask()
    {
        console.log(this.newTaskForm.value)
    }
}

《ngModule

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';

import { routing }        from './app.routing';
import { AppComponent }  from './app.component';
import { TaskService } from './task.service'

@NgModule({
    imports: [
        BrowserModule,
        routing,
        FormsModule
    ],
    declarations: [ AppComponent ],
    providers: [
        TaskService
    ],
    bootstrap: [ AppComponent ]
})
export class AppModule { }

这个问题

为什么会出现这个错误?我遗漏了什么吗?


当前回答

对于浏览这些线程的人来说。在我的情况下,我有一个共享模块,我只导出FormsModule和ReactiveFormsModule,忘记导入它。这导致了一个奇怪的错误,即表单组在子组件中不起作用。希望这能帮助那些摸不着头脑的人。

其他回答

请记住,如果你已经定义了“功能模块”,你需要在功能模块中导入,即使你已经导入到AppModule中。来自Angular文档:

模块不会继承对其他模块中声明的组件、指令或管道的访问权。AppModule导入的内容与ContactModule无关,反之亦然。在ContactComponent可以绑定[(ngModel)]之前,它的ContactModule必须导入FormsModule。

https://angular.io/docs/ts/latest/guide/ngmodule.html

在相应的模块中导入ReactiveFormsModule。

Angular 4结合特性模块(如果你使用的是共享模块)也要求你导出ReactiveFormsModule才能工作。

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports:      [
    CommonModule,
    ReactiveFormsModule
  ],
  declarations: [],
  exports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ]
})
export class SharedModule { } 

我几乎尝试了这里所有的解决方案,但我的问题有点不同(愚蠢)。 我在路由模块中添加了组件,但没有包括它的主模块。 所以要确保你的组件是模块的一部分。

假设你的应用结构如下:

AnotherModule < your_form > AppModule

根据您的表单类型,在AnotherModule中导入ReactiveFormsModule或FormsModule。

确保在AppModule中导入了AnotherModule。