双向绑定不起作用 [英] Two-way binding doesn't work

查看:203
本文介绍了双向绑定不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习Angular和Angular-CLI.因此,我使用Angular-CLI创建了一个项目,从一开始它似乎运行良好.现在,为了进行测试,我将app.component.html文件更改为以下内容:

I'm trying to learn Angular and Angular-CLI. So I created a project with Angular-CLI, which from the beginning seems to run just fine. Now for testing I changed app.component.html file to the following:

<h1>Input your name:</h1>
<input type="text" [(ngModel)]="name">
<p>Your input: {{ name }}</p>

和我的app.component.ts:

and my app.component.ts accordingly:

...
export class AppComponent {
  name = '';
}

我遇到了错误:

未捕获的错误:模板解析错误:由于以下原因无法绑定到"ngModel" 它不是'input'的已知属性.

Uncaught Error: Template parse errors: Can't bind to 'ngModel' since it isn't a known property of 'input'.

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

At this point for some reason nothing renders on the page. I tried to change the app.component.html to this:

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

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

Now the page renders correctly, I do see the input box, but as I type I don't see the two-way binding, I don't see the output in my <p> element.

为什么会发生,如何解决?

Why is it happening and how can it be fixed?

推荐答案

您只需在app.module.ts中导入FormsModule,您的问题将得到解决.像这样的东西.

You just have to import FormsModule in your app.module.ts & your issue will get resolved. Something like this.

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

这篇关于双向绑定不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆