私はAngularの初心者です。それを学ぶためにTour of Heroesを始めました。
そこで、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 { }
ここでエラーが発生しました。
Uncaught Error:予期しないモジュール 'FormsModule'がモジュール 'AppModule'によって宣言されています。Pipe/@Directive/@Componentのアノテーションを追加してください。
FormsModule "は "declarations array "ではなく、"imports array "に追加する必要があります。
BrowserModule
, FormsModule
, HttpModule
などのモジュールをインポートするためのものです。Components
, Pipes
, Directives
などのモジュールをインポートするためのものです。以下の変更点を参照してください。
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
FormsModule」をImports配列に追加します。
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
また、[(ngModel)]
を使わずに、<br/>.を使うことでも実現できます。
<input [value]='hero.name' (input)='hero.name=$event.target.value' placeholder="name">
の代わりに
<input [(ngModel)]="hero.name" placeholder="Name">