双向绑定不起作用

时间:2017-09-16 08:39:56

标签: angular angular-cli two-way-binding

我正在尝试学习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 = '';
}

我收到错误:

  

未捕获错误:模板解析错误:无法绑定到&#39; ngModel&#39;以来   它不是“输入”的已知属性。

此时出于某种原因,页面上没有任何渲染内容。我尝试将app.component.html更改为:

<input type="text" ng-model="name">
...

现在页面呈现正确,我确实看到了输入框,但是当我输入时我没有看到双向绑定,我在<p>元素中看不到输出

为什么会发生这种情况?如何解决?

1 个答案:

答案 0 :(得分:1)

您只需在FormsModule&amp;中导入app.module.ts即可。你的问题将得到解决。这样的事情。

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 { }