angular - ngModel 在 Angular4 中不起作用

标签 angular ngmodel

我正在从 official site 学习 Angular 4我来到了 2-way data binding through ngModel 的部分.但是,只要我将 [(ngModel)] 添加到我的组件模板,我的应用程序就会停止工作,即使 FormsModule 已导入到 module.ts 文件中。组件未加载。
我正在使用 Visual Studio Code。
这是我的 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"
     };
    }  

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

AppComponent 没有加载,只是显示

正在加载...

最佳答案

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

关于angular - ngModel 在 Angular4 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44794000/

相关文章:

javascript - 在另一个指令的点击事件上重新计算 ngx-datatable

angular - 工具提示未显示在正确的位置

javascript - 如何实现迭代、数组填充 Angular 2 输入?

angular - 如何编辑[(ngModel)]显示的值?

Angular - 具有多重绑定(bind)的 TextArea

html - @ViewChild 返回未定义的 Angular 8

angular - ng-cli : hidden . git 目录已创建?断开链接?

angular - 关于更新我的 Angular 项目的问题

angular - ngModel 在对象键上通过 ngFor 对象属性的双向数据绑定(bind)

angular - 选择上的 ngModel 不显示初始值、默认值