ngModel not working in Angular4

Deadly 提交于 2019-12-08 15:50:20

问题


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


回答1:


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:


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:


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

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



来源:https://stackoverflow.com/questions/44794000/ngmodel-not-working-in-angular4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!