Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Tags:

angular

I'm new in Angular. I started Tour of Heroes to learn it. So, I am created an app.component with two-way binding.

import { Component } from '@angular/core';
export class Hero {
    id: number;
    name: string;
}
@Component({
    selector: 'app-root',
    template: `
        <h1>{{title}}</h1>
        <h2>{{hero.name}}  details!</h2>
        <div><label>id: </label>{{hero.id}}</div>
        <div><label>Name: </label>
            <input [(ngModel)]="hero.name" placeholder="Name">
        </div>
    `,
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'Tour of Heroes';
    hero: Hero = {
        id: 1,
        name: 'Windstorm'
    };
}

Following the tutorial I imported FormsModule and added it into declarations array. Error appeared at this step:

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

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

Here is error:

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation.

like image 796
Vlad Poltorin Avatar asked Jul 11 '17 10:07

Vlad Poltorin


3 Answers

FormsModule should be added at imports array not declarations array.

  • imports array is for importing modules such as BrowserModule, FormsModule, HttpModule
  • declarations array is for your Components, Pipes, Directives

refer below change:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
like image 139
Pengyy Avatar answered Nov 17 '22 05:11

Pengyy


Add FormsModule in Imports Array.
i.e

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})

Or this can be done without using [(ngModel)] by using

<input [value]='hero.name' (input)='hero.name=$event.target.value' placeholder="name">

instead of

<input [(ngModel)]="hero.name" placeholder="Name">
like image 28
Praveen Ojha Avatar answered Nov 17 '22 06:11

Praveen Ojha


Remove the FormsModule from Declaration:[] and Add the FormsModule in imports:[]

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

like image 4
Fahim zuhair Avatar answered Nov 17 '22 05:11

Fahim zuhair