<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區域的值也對應變化了。