iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 8
0
Modern Web

從零開始的Angular前端開發系列 第 8

# DAY 8 Binding (二)

還有兩種 data binding 的方式,前面講的兩種都是將資料從 ts 送到 html ,今天來看看 Event binding 和 Two-way binding。

Event binding

當我們想在頁面上做一些互動、觸發事件時,就可以使用 Event binding 。比方說我們設計一個 button ,會將想要做的事情寫成 function 放在 ts 中,透過 Event binding ,在按下按鈕時執行這個 function,以下是一個簡單的例子:
語法跟前面的 property binding 很像,只是將中括號換成小括號:

()=""
// app.component.html
<p>{{context}}</p>
<button (click)="onClick()" >magic</button>
// app.component.ts
export class AppComponent {
    context = 'context';
    onClick() {
        this.context = 'context changed!';
    }
}

這邊將 buttonclick 屬性,綁定到 onClick() 這個 function。


當我按下 magic 後,觸發了 ts 中的 onClick() function ,更改了 context 的內容:

Event binding 像前面的 Property binding 類似,可以有別種寫法:

// app.component.html
<button on-click="onClick()" >magic</button>

Two-way binding

使用 Two-way binding 表示資料流是雙向的,即是說,在 html 更改了屬性的值,對應到在 ts 中的變數,也會跟著改變其值,反之亦然。其實可以把它看作是 Property binding 和 Event binding 的結合,語法如下:

[()] = ""

我們試試看對表單元素做 Two-way binding,由於原生的html沒有屬性是同時具有 value 跟 event 的特性,這個時候我們需要使用到 ngModel 來擔任這個角色:

// app.component.html
<input type="text" [(ngModel)]='number1'>
<input type="text" [ngModel]='number2'>
<button (click)="display()" >display</button>
// app.component.ts
export class AppComponent {
    number1 = 1;
    number2 = 2;
    display() {
        alert('number1 is ' + this.number1 +
        ', number2 is ' + this.number2);
  }

這邊主要功能是:
設定兩個 text 欄位和一個 button,兩個 text 分別綁定 number1number2 ,點擊 button 時會跳出提示框顯示 number1number2 的值。

但這樣還不能執行,使用 ngModel 必須先在 app.module.ts 中 import FormsModule

切換到 app.module.ts ,我們輸入 FormsModule 的前幾個字,如果有安裝 VSCODE 的 extention 的話, VSCODE 就會產生提示字,選 ng-import-FormsModule ,就會幫我們產生完整的 import 程式碼:

接著在 @NgModuleimports 中加入 FormsModule:

如此就可以使用 ngModel 了。

左邊是使用 Two-way binding 的 text , 右邊則是使用 Property binding。

按下 display :

那我們手動改變 text 中的值:

發現左邊的 text 因為使用Two-way binding,所以 number1跟著改變其值,但是 number2 則沒有:


上一篇
# DAY 7 Binding (一)
下一篇
# DAY 9 善用 Extensions 進行開發
系列文
從零開始的Angular前端開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言