本篇介紹如何實作Angular的雙向綁定(two-way binding),或稱雙向繫結的簡單教學。
首先用Angular CLI建立一個新專案,然後用VS Code開啟。
Two-way binding需用到@angular/forms的FormsModule,
所以先打開app.modules.ts,在@NgModule中匯入FormsModule。
app.modules.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; // <-- 加上FormsModule
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule // <-- 加上FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
接著開啟app.component.ts,在AppComponent類別中加入新的屬性content,作為與app.component.html的[(ngModel)]="content"進行雙向綁定的屬性。
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'demo';
content = ''; // <-- 雙向綁定的內容
}
接著修改app.component.html,把新專案預設的內容刪除,更改為下面內容。
app.component.html
<input type="text" name="content" [(ngModel)]="content"/>
<h1>{{content}}</h1>
在template實現雙向綁定的語法為[(...)],又稱為banana-in-box語法(盒子裡的香蕉)。
在[(...)]裡面使用Angular內建的directive ngModel來綁定domain model(AppComponen.content)與view(app.component.html)的html元素。
以上效果同下,可拆分為ngModel的property binding與ngModelChange的event binding,因此[()]其實是結合property binding與event binding的語法糖。Event binding的$event物件即為ngModel被修改後的內容ngModelChange。
app.component.html
<input type="text" name="content"
[ngModel]="content"
(ngModelChange)="content=$event"/>
<h1>{{content}}</h1>
完成以上設定後在瀏覽器的效果如下。
參考:
沒有留言:
張貼留言