因为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 中使用双向数据绑定了。