johnnyfittizio johnnyfittizio - 3 months ago 48
TypeScript Question

Can't bind to 'formGroup' since it isn't a known property of 'form'

THE SITUATION:

Please help! I am trying to make what should be a very simple form on my Angular2 app but no matter what it never work...

ANGULAR VERSION:

Angular 2.0.0 Rc5

THE ERROR:

Can't bind to 'formGroup' since it isn't a known property of 'form'


enter image description here

THE CODE:

The view:

<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>


The controller:

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)
}

}


The 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 { }


THE QUESTION:

Why I am getting that error?

I am missing something?

Answer

You need to import REACTIVE_FORM_DIRECTIVES from '@angular/forms' in your controller and add it to directives in @Component. That will fix the problem.

Edit:

After you fix that, you will probably get another error because you didn't add formControlName="name" to your input in form.

Comments