【问题标题】:Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation未捕获的错误:模块“AppModule”声明的意外模块“FormsModule”。请添加@Pipe/@Directive/@Component 注解
【发布时间】:2017-12-15 08:50:27
【问题描述】:

我是 Angular 的新手。我开始了英雄之旅来学习它。 所以,我用two-way 绑定创建了一个app.component

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 注解。

【问题讨论】:

  • 这是一个“模块”。它属于imports 而不是declarations

标签: angular


【解决方案1】:

FormsModule 应添加到 imports array 而不是 declarations array

  • imports array 用于导入模块,例如BrowserModuleFormsModuleHttpModule
  • 声明数组适用于您的ComponentsPipesDirectives

请参阅以下更改:

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

【讨论】:

  • 感谢您的回答和信息。它有帮助。
【解决方案2】:

在 Imports 数组中添加 FormsModule

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

或者这可以在不使用[(ngModel)] 的情况下使用

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

而不是

<input [(ngModel)]="hero.name" placeholder="Name">

【讨论】:

    【解决方案3】:

    Declaration:[] 中删除 FormsModule 并添加 FormsModule进口:[]

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

    【讨论】:

    • 那么,您的回答添加了什么其他人尚未提供的内容?
    【解决方案4】:

    您可以添加到declarations: [] in modules

    • 管道
    • 指令
    • 组件

    专业提示:错误消息解释它 - Please add a @Pipe/@Directive/@Component annotation.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-23
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 2018-03-14
      相关资源
      最近更新 更多