• 数据在组件类和组件模板中双向同步
  • Angular 将双向数据绑定功能放在了 @angular/forms 模块中,所以要实现双向数据绑定需要依赖该模块

    引入 FormsModule 模块

    ```typescript // src/app/app.module.ts import { FormsModule } from ‘@angular/forms’;

@NgModule({ imports: [FormsModule], })

export class AppModule {}

  1. <a name="hWKWN"></a>
  2. ### 使用双向数据绑定
  3. ```typescript
  4. <input type="text" [(ngModel)]="username" />
  5. <button (click)="change()">在组件类中更改 username</button>
  6. <div>username: {{ username }}</div>
  1. export class AppComponent {
  2. username: string = ""
  3. change() {
  4. this.username = "hello Angular"
  5. }
  6. }