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

Vla*_*rin 80 angular

我是Angular的新手.我开始了英雄之旅来学习它.所以,我创建了一个app.component具有two-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'
    };
}
Run Code Online (Sandbox Code Playgroud)

在本教程之后,我导入了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 { }
Run Code Online (Sandbox Code Playgroud)

这是错误:

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

Pen*_*gyy 212

FormsModule应该添加imports arraydeclarations array.

  • 进口阵列是用于导入模块,例如BrowserModule,FormsModule,HttpModule
  • 声明数组是你Components,Pipes,Directives

参考以下变化:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
Run Code Online (Sandbox Code Playgroud)


Pra*_*jha 9

添加FormsModule导入数组。

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
Run Code Online (Sandbox Code Playgroud)

或者,这可以在不使用进行[(ngModel)]

<input [value]='hero.name' (input)='hero.name=$event.target.value' placeholder="name">
Run Code Online (Sandbox Code Playgroud)

代替

<input [(ngModel)]="hero.name" placeholder="Name">
Run Code Online (Sandbox Code Playgroud)