我正在从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 回答
除了模块声明的
imports
部分中需要FormsModule
之外,还必须使用form
标记或ngForm
指令来启用ngModel
功能 .没有你也可以使用独立控件来像这样使用
ngModel
:资料来源:Angular documentation
然后在
@NgModule(){imports:[FormsModule]}
和其他工作人员一起