[Angular] 實現Two Way Binding

在MVC 中, Model 中的內容通常都要透過Binding 才可以顯示出來. 同樣地, 這裡會示範如何利用Angular 做data binding.

  1. 在之前的例子中, 於/app/theme/layout.component.ts 中修改內容:
    import { Component } from '@angular/core';
    
    @Component({
        moduleId: module.id,
        selector: 'layout',
        templateUrl: '/app/theme/layout.component.html'
    })
    export class LayoutComponent {
        Name: string;
        constructor() {
            this.Name = 'Apple';
        }
    }
    
  2. 在/app/theme/layout.component.html 中修改內容如下:
    <h4>{{Name}}</h4>
    <input type="text" [(ngModel)]="Name" id="Name" name="Name" />

    用作Binding 的, 主要是ngModel, 而[()] 決定binding 方法為雙向(two-way), {{}} 則為單向 (One-way).

  3. 執行後, 見到textbox 而內容修改後, 上邊的<div> 能跟著改變, 視為成功.2016-12-06-17_56_39-pc0238v-vs2015-vmware-workstation
About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.