Angular双向绑定的一个例子

[(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
~~~~~~~~~~~~~~~~~~~~~~~

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区域的值也对应变化了。

要获取更多Jerry的原创文章,请关注公众号"汪子熙":


你可能感兴趣的:(Angular双向绑定的一个例子)