转载自 http://www.ngui.cc/news/show-117.html
使用过 AngularJS 1.x 的同学,应该很熟悉 ng-model 指令,通过该指令我们可能方便地实现数据的双向绑定。而在 Angular 中,我们是通过 ngModel 指令,来实现双向绑定。
使用双向绑定
引入 FormsModule
import {FormsModule} from "@angular/forms";
@NgModule({ // ...
imports: [
BrowserModule,
FormsModule
], // ... })
export class AppModule { }
使用 ngModel 指令
@Component({
selector: 'app-simple-form',
template: `
<div>
{{message}}
<input #myInput type="text" [(ngModel)]="message">
<button (click)="onClick($event, myInput.value)">点击</button>
</div>
`,
styles: []
})
export class SimpleFormComponent implements OnInit { // ...}
上面示例中,我们使用 [(ngModel)]="message" 语法实现数据的双向绑定。该语法也称作 Banana in the Box 语法,即香蕉在盒子里 (比较形象生动,记忆该语法)。