这种情况

我试图在我的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 { }

这个问题

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


当前回答

我也有同样的问题,问题实际上只是我忘记导入和声明在模块中保存表单的组件:

import { ContactFormComponent } from './contact-form/contact-form.component';

@NgModule({
    declarations: [..., ContactFormComponent, ...],
    imports: [CommonModule, HomeRoutingModule, SharedModule]
})
export class HomeModule {}

其他回答

import {FormsModule, ReactiveFormsModule} from '@angular/forms'; 并将其添加到app-module的imports数组中。ts文件。

假设你的应用结构如下:

AnotherModule < your_form > AppModule

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

确保在AppModule中导入了AnotherModule。

如果正确导入了FormModule和ReactiveFormModule,可能会出现另一个问题。也许你没有将你的组件添加到app模块的模块声明中。所以把你的组件添加到app.module.ts声明中:

@NgModule({
  declarations: [
    YourNewComponent
  ]
})

如果这只是一个TypeScript错误,但是表单上的一切都正常,你可能只需要重新启动你的IDE。

可以导入formModule和reactiveFormModule

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


@NgModule({
    declarations: [
        ContactComponent
    ],
    imports: [
        CommonModule,
        ContactRoutingModule,
        FormsModule,
        ReactiveFormsModule
    ]
})
export class ContactModule { }