Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation
AngularAngular Problem Overview
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.
Angular Solutions
Solution 1 - Angular
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]
})
Solution 2 - Angular
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">
Solution 3 - Angular
Remove the FormsModule from Declaration:[] and Add the FormsModule in imports:[]
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
Solution 4 - Angular
Things you can add to declarations: [] in modules
- Pipe
- Directive
- Component
Pro Tip: The error message explains it - Please add a @Pipe/@Directive/@Component annotation.