首页 文章

ngModel在Angular4中不起作用

提问于
浏览
9

我正在从official site学习Angular 4,我来到2-way data binding through ngModel . 但是,一旦我将[(ngModel)]添加到我的组件模板,我的应用程序就会停止工作,即使在module.ts文件中导入了FormsModule . 组件无法加载 .
我正在使用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未加载,只显示

载入中...

4 回答

  • 15
    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 { }
    
  • 2
    // add the import in module and add FormModule in import:
    import { NgModule } from '@angular/core'
     imports: [
        BrowserModule,
       // add FormModule in import
        FormsModule
    ]
    
  • 3

    除了模块声明的 imports 部分中需要 FormsModule 之外,还必须使用 form 标记或 ngForm 指令来启用 ngModel 功能 .

    没有你也可以使用独立控件来像这样使用 ngModel

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

    资料来源:Angular documentation

  • 0
    import { FormsModule } from '@angular/forms';
    

    然后在 @NgModule(){imports:[FormsModule]} 和其他工作人员一起

相关问题