iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 13
0
Modern Web

Angular初期筆記系列 第 13

DAY13-Angular6之data binding-Two-way data binding

  • 分享至 

  • twitterImage
  •  

Two-way data binding with ngModel (中文:使用 ngModel 的 雙向繫結)

當開發數據輸入表單時,通常都會顯示 data property 並在用戶進行更改時更新該 property

Two-way data binding 要使用 NgModel directive 會更容易

FormsModule 是使用 NgModel 必須匯入的項目
在使用 NgModel directive 達到雙向資料綁定前,你必須要匯入 FormsModule 到 @NgModule 的 imports 清單
https://angular.io/guide/template-syntax#ngmodel---two-way-binding-to-form-elements-with-ngmodel

Step1:匯入 FormsModule

src/app/app.module.ts
-----
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // 匯入點

@NgModule({
imports: [
        BrowserModule,
        FormsModule // 匯入點
    ],
})
export class AppModule { }

Step2:添加變數和 html 標籤

app\app.component.ts
-----
export class AppComponent implements OnInit {
    something = '我是something';
    showMyValue = '我是showMyValue';
}
app\app.component.html
-----
<input type="text" [(ngModel)]="something">
{{something}}
<input type="text" (input)="showMyValue = $event.target.value">
{{showMyValue}}

顯示

https://ithelp.ithome.com.tw/upload/images/20181023/20107754N7E3mRGfDF.png

這邊可以看到雙向繫結和單純使用 click 事件的差異,使用 click 事件初始並無法綁定值

Step3:讓第二個 input 綁定值

app\app.component.html
-----
<input type="text" [(ngModel)]="something">
{{something}}
<input type="text" [value]="showMyValue" (input)="showMyValue = $event.target.value">
{{showMyValue}}

顯示
https://ithelp.ithome.com.tw/upload/images/20181023/20107754eiqibJmxeL.png

ngModel directive 幫你隱藏了繁重的細節,讓你只要使用 ngModel 匯入和 ngModelChange 輸出 就可以了!
https://angular.io/guide/template-syntax#ngmodel---two-way-binding-to-form-elements-with-ngmodel

Step4:將 [(ngModel)]="something" ,拆開

app\app.component.html
-----
<input type="text" (ngModel]="something" (ngModelChange)="something = $event">
{{something}}
<input type="text" [value]="showMyValue" (input)="showMyValue = $event.target.value">
{{showMyValue}}

這種寫法,就可以讓雙向繫結的 改變事件,添加自定義事件

後話

data binding 是傳遞參數最重要的橋樑,原先是打算在 3 篇內寫完,但是看完 Angular 官網再實際撰寫,發現每一個 data binding 方法介紹,都有些許是還未使用到的,故消化吸收後再吐出來,幾乎都超過原先想撰寫內容,並幾乎都超過 300 字太多了!就變成了 data binding 六連發XD~

DAY10-Angular6之data binding-Attribute
這篇是最少人看的(不算意外畢竟在JS的世界~),但私心推薦一下,它真的不好懂,但看懂可以避免掉 Attribute 和 Property 的誤區,不至於滿頭問號!


上一篇
DAY12-Angular6之data binding-Style
下一篇
DAY14-Angular6之樣板參考變數-實作
系列文
Angular初期筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言