Skip to content

Templates#

Binding#

DOM Property Binding#

  • {{ value }} is called Interpolation
  • Property Binding uses []
    • also called source-to-view
  • 舉例:
    <img [src] = "picUrl"> 相等於 <img bind-src = "picUrl">
    

HTML Attribute Binding#

  • 多數的 HTML Attribute 會對應到 DOM Property
  • 某些 Attribute 只是單純的 Attribute
    • ARIA、SVG、Table 跨行跨列的 span
  • 舉例:
    ❌ : <svg width = "{{ 100 + 100 }}" ></svg>
    ⭕ : <svg [attr.width] = "{{ 100 + 100 }}" ></svg>
    

Class Binding#

  • CSS class 綁定也是一種屬性綁定

    .ts

    classes = "big blue";
    

    .html

    <div [class] = "classes"></div>
    

  • ngClasses

    [ngClass] = "classes"
    [ngClass] = "{ ‘big': true }""
    

Event Binding#

  • View to source
  • 使用 (事件) 或是 on-事件
  • 舉例

    (click) = "SayHi()" 相等於 on-click = "SayHi()"
    
  • Bubbling (冒泡)

    • 事件由內向外
    • 舉例:
      <div (click) = "onClick('div')"">
          <button (click) = "onClick('button')"></button>
      </div>
      
    • 上面事件會先由button的event先觸發,再來才是div的
    • 可以使用stopPropagation() 來阻止冒泡
      onClick(e: event) { e.stopPropagation() }
      

$event 事件處理訊息#

  • 相當於DOM物件的event物件
  • 綁定會通過這個傳遞關於此事件的資訊
  • event 物件
    • event.target: 原始目標 → 觸發的對象
    • event.currentTarget: 當前這個目標 → 監聽的對象
    • event.target.value
  • 提供 DOM Event 的相關方法
    • preventDefault → 取消事件預設行為
    • stopPropagation → 取消事件傳遞行為
    • stopImmediatePropagation → 馬上取消所有的事件傳遞行為
      • DOM Level 3 新增的功能
  • 下拉清單使用 $event.target
    • 觸發事件的目標物件

[ngModel]、(ngModelChange)#

  • 提供表單控制項的綁定能力
  • 需要使用 NgModule、FormsModule
  • [ngModel] → source to view → 數據綁定
  • (ngModelChange) → view to source → 事件綁定

[(ngModel)]#

  • 雙向綁定,view-to-source-to-view
  • 只能用在HTML中
  • @input → 宣告自訂元素的輸出屬性
  • @output → 宣告自訂元素的是件通知
  • EventEmitter → 定義事件的傳遞訊息型別
  • 自訂的元素需要注意:
    • @output 名稱必須是 @input + 事件名稱
    • 舉例:
      @Input() searchText: string;
      @Output() searchTextChange = new EventEmitter<string>();
      
    • EventEmitter 使用 emit 傳遞事件參數
      onSearch(search: string) {
          this.searchText = search;
          this.searchTextChange.emit(this.searchText);
      }
      

Style Binding#

  • 使用 [style.attribute]

    <h3 [style.border] = "mySearch.length > 0? 'solid 3px blue': 'solid 3px red' ">
    

  • 有多個style要設定時,使用ngStyle

    this.styles = {.............................}
    <h3 [ngStyle] = "styles">
    


Pipe#

用來對於字串、日期、數字、貨幣等等資料進行轉換及格式化
內建:

Pipe 用途
UpperCasePipe uppercase
LowerCasePipe lowercase
DatePipe date
CurrencyPipe currency
DecimalPipe number
PercentPipe percent
{{ myDate | date: shortDate }}