ngModel在Angular4中不起作用 [英] ngModel not working in Angular4

查看:146
本文介绍了ngModel在Angular4中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从官方网站学习Angular 4,我来到了

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"
     };
    }  

这是app.module.ts

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

AppComponent未加载,仅显示

The AppComponent is not loaded and just shows

正在加载...

推荐答案

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

这篇关于ngModel在Angular4中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆