上一篇文章,我們介紹了動態處理資料的字串插值,這篇會介紹另一個重要技術:Binding
[]
來綁定屬性值,動態更新資料。[disabled]="isDisabled"
<!-- `isDisabled` 為 `true` 時,按鈕會被禁用 -->
<button [disabled]="isDisabled"></button>
<!--
雖然看起來像是在綁定 `<img>` 標籤本身的 src 屬性 ,但實際上是會將底層 HTMLImageElement DOM 物件的 src 屬性綁定到 `someSrc` 變數中儲存的值。
-->
<img [src]="someSrc">
<!--
當綁定 ARIA 屬性時,無法針對底層 DOM 物件屬性進行操作,因為這些屬性沒有對應的物件屬性,
因此可以透過在想要動態綁定的屬性名稱前面加上 `attr`,來綁定到 HTML 的屬性(attribute)上
-->
<div
[attr.aria-valuenow]="currentVal"
[attr.aria-valuemax]="maxVal"
aria-valuemin="0">
...
</div>
<img src="profile-photo.jpg" alt="Profile photo of {{ firstName }}" >
attr.
,來區別是綁定 HTML 屬性還是 DOM 屬性。<button attr.aria-label="Save changes to {{ objectType }}">
[class.className]
語法,將 class 名稱與布林值綁定。[class]="className1 className2"
[class]="{ className1: condition1, className2: condition2 }
[class]="['className1', 'className2']
<div [class.active]="isActive"
[class]="{ 'text-large': isLargeText, 'text-bold': isBoldText }">
Content>
</div>
[style.property]
語法,將 CSS 屬性名稱與值綁定。
-
:連字符(dash)會被轉換為駝峰式命名(camelCase),例如 font-size
會變成 fontSize
。px
、rem
等。 [style.fontSize.px]="value"
或[style.fontSize.rem]="value"
[style]="property1: value1; property2: value2"
[style]="{ 'property1': value1, 'property2': value2 }
<h2 [style.font-size]="'5rem'">
Title
<h2>
今日目標,依照模板建立 Todo List 的元件結構
今天介紹了 Angular 中的繫結技術,這是讓應用程式能夠動態更新資料和樣式的關鍵技術。下一篇來介紹 event listeners 事件監聽,讓我們能夠處理使用者互動事件。