2017-07-11 21 views
10

Jestem nowa w Angular. Rozpocząłem Tour of Heroes, aby się tego nauczyć. Tak więc utworzono wiązanie app.component z two-way.Uncaught Error: Nieoczekiwany moduł "FormsModule" zadeklarowany przez moduł "AppModule". Dodaj @ Pipe/@ Directive/@ Adnotacja komponentu

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

Po samouczku zaimportowałem moduł FormsModule i dodałem go do tablicy deklaracji. Błąd pojawił się w tym kroku:

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

Oto błąd:

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

+0

Jest to "moduł". Należy do "importu", a nie "deklaracji". –

Odpowiedz

29

FormsModule powinny być dodane w imports array nie declarations array.

  • import array jest do importowania modułów, takich jak BrowserModule, FormsModule, HttpModule
  • deklaracje tablicę dla waszej Components, Pipes, Directives

patrz poniżej zmiany:

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

Dziękuję za odpowiedź i informacje. Pomogło. –

0

Dodaj FormsModule w tablicy importu.
tj

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

Albo można to zrobić bez użycia [(ngModel)] za pomocą

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

zamiast

<input [(ngModel)]="hero.name" placeholder="Name"> 
Powiązane problemy