iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 4
0
Modern Web

Angular - 從零開始系列 第 4

Angular - 從零開始 - Day4 -屬性繫結 Property Binding

angular

基礎認識

屬性使用中括號包住,並等於一個陳述式,使用引號包住,EX. [屬性]='陳述內容'。

延續內嵌繫結來改寫,將 href 改成屬繫繫結,其值為 url,url 的值就是原本的連結內容。

<a [href]="url">屬性繫結</a>

component 的內容沒有改變。

import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"],
})
export class AppComponent {
  title = "property binding";
  url = "https://hsuchihting.github.io/";
}

延伸使用

這個方法好用的地方是當屬性內容會改變時,就可以善加利用屬性繫結去做撰寫,例如:

  1. 滑鼠移動到圖片上顯示 title 內容。
  2. 圖片為變動圖片連結時。

原本圖片連結與加入 title 寫法是這樣:

<img title="pic title" src="https://url.joor.net/ckY" alt="pic" />

使用屬性繫結的方法改寫後會變這樣:

<img [title]="str" [src]="imgUrl" alt="pic" />

相對應的 component 的內容如下:

import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"],
})
export class AppComponent {
  title = "property binding";
  url = "https://hsuchihting.github.io/";
  str = "pic title";
  imgUrl = "https://url.joor.net/ckY";
}

property 與 attribute 是不同的

雖然 property 與 attribute 的中文都翻譯成「屬性」,但在 HTML5 中,attribute 是可以自定義的,例如: data-setAttributeName,可是無法作為屬性繫結。

那實際差別是什麼?

attribute

簡單來說 atrribute 是標籤的屬性,以下方這行標籤為例:

<img title="pic title" src="https://url.joor.net/ckY" alt="pic" />

像是 imgsrctitlealt 為標籤屬性,另外還有很常見的 hrefclass...等。

property

如果是想要看見 img 這個 DOM 元素底下有什麼屬性可以使用,所以屬於 JavaScript 底下的 property,可以透過開發人員工具中的 properties 找到許多這個 img 這個網頁元素可以使用的屬性,所以屬性繫結是綁定 DOM 元素底下可以使用的屬性,非 attribute。

所以如果要用屬性繫結一樣的方法去綁定自定義的屬性名稱是沒有辦法的,因為會找不到,但是可以在前面加上一個 attr 就可以使用自定義的屬性囉!其值內容也可以從 component 而來。

EX. [attr.data-setName]='statement


上一篇
Angular - 從零開始 - Day3 -內嵌繫結 Interpolation
下一篇
Angular - 從零開始 - Day5 -事件繫結 Event Binding
系列文
Angular - 從零開始25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言