ngModel data binding not working

2020-02-15 11:07发布

问题:

I'm following the Tour of Heroes tutorial and cannot figure out why ngModel is not updating hero.name or if it's just not updating the view. I type into the input but the displayed name in the view remains the same (Windstorm).

Please let me know what I am doing wrong here.

heroes.component.html

<h2>{{ hero.name | uppercase }}</h2>
<div><span>id: </span>{{ hero.id }}</div>
<div>
  <label>name
    <input ([ngModel])="hero.name" placeholder="name">
  </label>
</div>

heroes.component.ts

import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
  hero: Hero = {
    id: 1,
    name: 'Windstorm'
  };
  constructor() { }

  ngOnInit() {
  }

}

hero.ts

export class Hero {
  id: number;
  name: string;
}

回答1:

([ngModel]) should be [(ngModel)]. It's called the bananas-in-a-box-notation ;) (https://www.bennadel.com/blog/3008-two-way-data-binding-is-just-a-box-of-bananas-in-angular-2-beta-1.htm)



回答2:

Open AppModule (app.module.ts) and import the FormsModule symbol from the @angular/forms library.

import { FormsModule } from '@angular/forms'; // <-- NgModel lives here

Then add FormsModule to the @NgModule metadata's imports array, which contains a list of external modules that the app needs.

imports: [
  BrowserModule,
  FormsModule
],

When the browser refreshes, the app should work again. You can edit the hero's name and see the changes reflected immediately in the above the textbox.


source: angular doc.