ngModel not working in Angular4

Mavil picture Mavil · Jun 28, 2017 · Viewed 37k times · Source

I am learning Angular 4 from the official site and I came to the part with 2-way data binding through ngModel. However, my app stops working as soon as I add [(ngModel)] to my component template, even though the FormsModule is imported in the module.ts file. The component does not load.
I am using Visual Studio Code.
This is my app.component.ts

import { Component } from '@angular/core';

    export class Hero {
      id: number;
      name: string;
    }



    @Component({
      selector: 'app',
      template: `
      <h1>{{ title }}</h1>
      <h2>{{hero.name}} details!</h2>
      <div><label>Id:</label> {{hero.id}} </div>
      <div>name:<input [(ngModel)]="hero.name" type="text"></div>
      `,
      styles:[`
        .selected{
          transition: padding 0.3s;
          color: mediumseagreen;
        }
      `]
    })

    export class AppComponent {
      title = 'Tour Of Heroes';

     hero:Hero = {
       id:1,
       name:"Mr. Invisible"
     };
    }  

This is app.module.ts

import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

    import { AppComponent, Hero } from './app.component';

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

The AppComponent is not loaded and just shows

Loading...

Answer

Rahul Singh picture Rahul Singh · Jun 28, 2017
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

    import { AppComponent, Hero } from './app.component';

    @NgModule({
      declarations: [
        AppComponent

      ],
      imports: [
        BrowserModule,
        FormsModule  // forms module should be in imports not in declarations
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }