因爲angular中並沒有默認雙向綁定,需要載入一個功能,纔可以使用。
<p>{{ message }}</p>
<input type="text" [(ngModel)]="message">
運行之後就報錯了,原因是使用 ngModel 必須導入 FormsModule 並把它添加到 Angular 模塊的 imports 列表中。
導入 FormsModule 並讓 [(ngModel)] 可用的代碼如下:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
+++ import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
+++ FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
通過以上的配置之後,就可以在 Angular 中使用雙向數據綁定了。