双向绑定¶
数据绑定可以将类中的数据绑定到网页上,想要将网页的数据绑定到类中,可以使用双向绑定
双向绑定可以通过两种方式实现
第一种¶
在类中写入:
app.component.ts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import { Component, OnInit, OnChanges } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent{ title = 'SampleApp'; message: string = "message"; onButtonClick(){ alert("message:"+this.message); } } |
类中定义了一个message变量和一个onButtonClick方法,方法执行时会弹出对话框,显示message的内容
html中写入:
app.component.html:
1 2 | <input [value]="message" (input)="message=$event.target.value"/> <button type="button" (click)="onButtonClick()">button</button> |
input标签中,将message的内容绑定到了input的value属性上,然后在input标签的input方法绑定到了message属性上
button点击时会执行onButtonClick方法
网页上改变input的值时再点击button,效果如下:

第二种¶
类中的写法和第一种一样,在html的处理稍有不同
首先在app.module.ts中导入FormsModule模块,这个模块可以实现表单控件的双向绑定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; //导入模块 import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule //加载到项目中 ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
然后在html中写入:
1 2 | <input [(ngModel)]="message" /> <button type="button" (click)="onButtonClick()">button</button> |
[(ngModel)]同时实现了将数据从类绑定到页面和页面绑定到类中
效果和第一种是一样的,这种更简洁一些
效果如下:
