Angular - Property Binding

  • 1045
  • 0
  • 2018-05-08

Property Binding (屬性繫結)

[property] = 'statement'

Property Binding

在HTML的Property 加上中括號,後面給定義在component.ts的變數名稱,就可以實現property binding

例如在template:component.html 內

href 這一個 DOM的property 加上中括號

<a [href]="href">{{title}}</a>

在 component.ts 內定義 property: href

export class HeaderComponent implements OnInit {

  title = '';
  href = '';

  constructor() {
    this.title = 'Google Title';
    this.href = 'http://www.google.com.tw';
  }

  ngOnInit() {}
}

即可完成Property Binding

Property 跟 Attribute 的不同

兩個都是翻成屬性,但是意義不同


Property => 意思是指這個 DOM 的Property,也就是Javascript的Property

要如何看這個DOM有哪些property,

F-12 打開檢查,點選要檢視的DOM物件,選擇右下角的頁籤Properties,

在不同的物件層級底下,可以看到這個DOM的Property

Property binding 真正的對象就是這個DOM 的 Property,而不是指HTML的Attribute

PS.在component.ts內自行定義的屬性(變數),也會稱為property

 

Attribute => 意思是指 HTML 的 Attribute(包含HTML5 提供的自訂擴充Attribute )


在HTML內如果要自訂擴充HTML Attribute,在HTML5是有明確定義的,

可以透過 data-Attribute,自由的擴充Attribute在標籤裡面

例如 

<a [href]="href" [title]="title" [data-dattribute]="要擴充的值">{{title}}</a>

但是這樣自訂擴充的Attribute 是不能夠直接使用Property Binding ,

如果要動態的綁定自訂的HTML Attribute

在Angular裡面標準的作法是前面加上 attr.

[attr.data-dattribute]="title"

完整的component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  title = '';
  href = '';

  constructor() {
    this.title = 'Google Title';
    this.href = 'http://www.google.com.tw';
  }

  ngOnInit() {}
}

完整的Template: component.html

<div class="container">
    <div class="row">
        <a [href]="href" [title]="title" [attr.data-dattribute]="title">{{title}}</a>
    </div>
</div>

執行後,點選F12 ,可看到我自行擴充的HTML Attribute 已經動態綁定了ts定義的變數 title