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

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

问题描述

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

输入你的名字:

<input type="text" [(ngModel)]="name"><p>您的输入:{{ name }}</p>

和我的 app.component.ts 相应:

<预><代码>...导出类 AppComponent {名称 = '';}

我收到错误:

<块引用>

未捕获的错误:模板解析错误:无法绑定到ngModel",因为它不是输入"的已知属性.

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

...

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

为什么会发生,如何修复?

解决方案

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

import { NgModule } from '@angular/core';从'@angular/platform-b​​rowser' 导入 { BrowserModule };从'@angular/forms'导入{FormsModule};从 './app.component' 导入 { AppComponent };@NgModule({进口:[ BrowserModule,FormsModule ],声明:[ AppComponent ],引导程序:[ AppComponent ]})导出类 AppModule { }

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>

and my app.component.ts accordingly:

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

I'm getting the error:

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

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">
...

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?

解决方案

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天全站免登陆