ngModel not working in Angular4

2019-06-16 07:00发布

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...

4条回答
We Are One
2楼-- · 2019-06-16 07:35
import { FormsModule } from '@angular/forms';

Then at @NgModule(){imports:[FormsModule]} with other staff

查看更多
甜甜的少女心
3楼-- · 2019-06-16 07:42

In addition of FormsModule needed in the imports section of the module declaration, you have to use a form tag, or a ngForm directive to enable the ngModel functionalities.

Withoutou can also use a standalone control to use ngModellike this :

 <input [(ngModel)]="variable" #ctrl="ngModel" >

Source :Angular documentation

查看更多
虎瘦雄心在
4楼-- · 2019-06-16 07:52
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 { } 
查看更多
三岁会撩人
5楼-- · 2019-06-16 07:53
// add the import in module and add FormModule in import:
import { NgModule } from '@angular/core'
 imports: [
    BrowserModule,
   // add FormModule in import
    FormsModule
]
查看更多
登录 后发表回答