ngModel不在Angular4中工作
我正在学习Angular 4,我是带着这个角色来的。但是,只要我将[(ngModel)]添加到组件模板中,我的应用程序就会停止工作,即使FormsModule已导入module.ts文件中。组件未加载。ngModel不在Angular4中工作,angular,ngmodel,Angular,Ngmodel,我正在学习Angular 4,我是带着这个角色来的。但是,只要我将[(ngModel)]添加到组件模板中,我的应用程序就会停止工作,即使FormsModule已导入module.ts文件中。组件未加载。 我正在使用Visual Studio代码。 这是我的app.component.ts import { Component } from '@angular/core'; export class Hero { id: number; name: string;
我正在使用Visual Studio代码。
这是我的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"
};
}
AppComponent未加载,仅显示
加载…除了模块声明的
imports
部分所需的FormsModule
之外,您必须使用form
标记或ngForm
指令来启用ngModel
功能
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
,如下所示:
<input [(ngModel)]="variable" #ctrl="ngModel" >
资料来源:
然后在
@NgModule(){imports:[FormsModule]}
与其他员工一起正如其他人指出的那样,导入FormsModule
是很重要的(例如,在您的app.module.ts
文件中)。在这个特定的问题中,导入部分缺少它
但我加上这个答案是为了警告你我不时遇到的其他事情
如果只使用ngModel
独立,而没有表单,则不必为输入指定名称
<input ... [(ngModel)]="model.something"`>
它实际上在文档中:
在标记中使用ngModel时,还需要提供name属性,以便控件可以在父窗体中以该名称注册
如果你错过了,它根本不会显示任何错误,它就是不起作用。错误是什么?你能显示错误消息和一些代码吗?@Sajeetharan:我刚才也有同样的错误。这一页还是空白的。命令行上没有错误。在Javascript控制台(在Chrome中)中,它表示“无法绑定到‘ngModel’,因为它不是‘input’的已知属性”。对于因此错误而来到这里的任何其他人:教程解释了错误以及如何修复它。你只需要继续学习教程就可以修复这个错误。检查这篇文章,答案很棒!比其他代码要好得多,它们只是代码。@Michael我想代码的这一行上有注释,表单模块导入应该会修复它。
// add the import in module and add FormModule in import:
import { NgModule } from '@angular/core'
imports: [
BrowserModule,
// add FormModule in import
FormsModule
]
import { FormsModule } from '@angular/forms';
<input ... [(ngModel)]="model.something"`>
<form>
<input ... name="something" [(ngModel)]="model.something"`>
</form>