未捕获的错误: 由模块‘ AppModule’声明的意外模块‘ FormsModule’。请添加@Pipe/@Directive/@Component 注释

我是新来的,我开始学习英雄之旅。 因此,我创建了一个 app.componenttwo-way绑定。

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'
};
}

根据本教程,我导入了 FormsModule 并将其添加到声明数组中:

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

这里有一个错误:

未捕获的错误: 由模块‘ AppModule’声明的意外模块‘ FormsModule’。请添加@Pipe/@Directive/@Component 注释。

135924 次浏览

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

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

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

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


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.