双向绑定不起作用
Two-way binding doesn't work
我正在尝试学习 Angular 和 Angular-CLI。所以我用 Angular-CLI 创建了一个项目,从一开始似乎 运行 就好了。现在为了测试,我将 app.component.html 文件更改为以下内容:
<h1>Input your name:</h1>
<input type="text" [(ngModel)]="name">
<p>Your input: {{ name }}</p>
和我的 app.component.ts 相应地:
...
export class AppComponent {
name = '';
}
我遇到错误:
Uncaught Error: Template parse errors: Can't bind to 'ngModel' since
it isn't a known property of 'input'.
此时由于某种原因,页面上没有呈现任何内容。我试图将 app.component.html 更改为:
<input type="text" ng-model="name">
...
现在页面正确呈现,我确实看到了输入框,但是在我键入时我没有看到双向绑定,我没有在我的 <p>
元素中看到输出。
为什么会发生这种情况,如何解决?
您只需在 app.module.ts
中导入 FormsModule
,您的问题就会得到解决。像这样。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
我正在尝试学习 Angular 和 Angular-CLI。所以我用 Angular-CLI 创建了一个项目,从一开始似乎 运行 就好了。现在为了测试,我将 app.component.html 文件更改为以下内容:
<h1>Input your name:</h1>
<input type="text" [(ngModel)]="name">
<p>Your input: {{ name }}</p>
和我的 app.component.ts 相应地:
...
export class AppComponent {
name = '';
}
我遇到错误:
Uncaught Error: Template parse errors: Can't bind to 'ngModel' since it isn't a known property of 'input'.
此时由于某种原因,页面上没有呈现任何内容。我试图将 app.component.html 更改为:
<input type="text" ng-model="name">
...
现在页面正确呈现,我确实看到了输入框,但是在我键入时我没有看到双向绑定,我没有在我的 <p>
元素中看到输出。
为什么会发生这种情况,如何解决?
您只需在 app.module.ts
中导入 FormsModule
,您的问题就会得到解决。像这样。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }