Skip to content

資料繫結 | Angular 新手練功日誌

· 4 min

上一篇文章,我們介紹了動態處理資料的字串插值,這篇會介紹另一個重要技術:Binding

繫結 Binding#

屬性繫結 Property Binding#

<!-- `isDisabled` 為 `true` 時,按鈕會被禁用 -->
<button [disabled]="isDisabled"></button>
<!--
雖然看起來像是在綁定 `<img>` 標籤本身的 src 屬性 ,但實際上是會將底層 HTMLImageElement DOM 物件的 src 屬性綁定到 `someSrc` 變數中儲存的值。
-->
<img [src]="someSrc">

屬性值繫結 Attribute Binding#

<!--
當綁定 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 }}" >
<button attr.aria-label="Save changes to {{ objectType }}">

類別繫結 Class Binding#

<div [class.active]="isActive"
[class]="{ 'text-large': isLargeText, 'text-bold': isBoldText }">
Content>
</div>

樣式繫結 Style Binding#

<h2 [style.font-size]="'5rem'">
Title
<h2>

專案實作#

今日目標,依照模板建立 Todo List 的元件結構

結論#

今天介紹了 Angular 中的繫結技術,這是讓應用程式能夠動態更新資料和樣式的關鍵技術。下一篇來介紹 event listeners 事件監聽,讓我們能夠處理使用者互動事件。