Angular双向绑定的一个例子

时间:2022-07-23
本文章向大家介绍Angular双向绑定的一个例子,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
<div>
    <label>name:
      <input [(ngModel)]="hero.name" placeholder="name"/>
    </label>
  </div>

[(ngModel)] is Angular’s two-way data binding syntax. Here it binds the hero.name property to the HTML textbox so that data can flow in both directions: from the hero.name property to the textbox, and from the textbox back to the hero.name.

ngModel是Angular的双向绑定语法,将Angular model的hero.name属性绑定到了HTML input字段上,这样数据流可以在hero.name属性和input字段之间双向传递。

上面的代码会导致如下错误:

Failed to compile.

src/app/heroes/heroes.component.html:7:14 - error NG8002: Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’.

7 <input [(ngModel)]=“hero.name” placeholder=“name”/> ~~~~~~~~~~~~~~~~~~~~~~~

src/app/heroes/heroes.component.ts:6:16 6 templateUrl: ‘./heroes.component.html’, ~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component HeroesComponent.

原因是因为缺少FormsModule 的导入。

在app.module.ts里导入FormsModule:

再加入@NgModule的imports区域:

最后效果如下:

只要更改input field里的值,h2区域的值也对应变化了。