iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 10
0
Modern Web

Angular初期筆記系列 第 10

DAY10-Angular6之data binding-Attribute

Attribute binding (中文:屬性繫結)

你可以設定一組值到屬性中成為 attribute binding

筆記:
這是一個 data binding 在綁定目標 property 的例外,也是唯一可以透過綁定給予 attribute 值的辦法

這邊要反覆強調,設定 element 的 property,在 property binding 中並需要使用 字串,為什麼 Angular 要提供 attribute binding?

你可以使用 attribute binding 當沒有 element property 可以綁定的時候。

考慮 ARIA,SVG 和 table span 的 attributes ,他們是純 attributes,並沒有對應的 element properties ,所以無法設置 element properties ,也就沒有 property 目標可以去綁定。
https://angular.io/guide/template-syntax#attribute-binding

在 JS 的世界所能影響到的就只有 property ,若想要進一步影響只能先把 attributes 變成可以控制的狀態( attr. ),這樣就可以藉由 JS 去影響到 html attributes 。

html attributes 項目
https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes

實作 html 元素 attribute 值中運算

當使用到 JS 的功能,元素的 attribute 就已經不在連結中了,轉為替代要使用 DOM 的 property 去連結回 html attribute

td 的 attribute (colspan) :https://www.w3schools.com/tags/tag_td.asp
td 的 property (colSpan) : https://www.w3schools.com/jsref/dom_obj_tabledata.asp

範例一:在 attribute 值中進行運算

先使用 Interpolation(中文:插入),放置 attribute 內

app\app.component.html
-----
<table border="1px">
    <tr>
        <td>
            第一行
        </td>
        <td>
            第二行
        </td>
    </tr>
    <tr>
        <td colspan={{1+1}}>
            12345
        </td>
    </tr>
</table>

顯示
https://ithelp.ithome.com.tw/upload/images/20181020/20107754KIIi4nSbO7.png

console
Uncaught Error: Template parse errors:
Can't bind to 'colspan' since it isn't a known property of 'td'.

範例二:直接使用 html DOM 的 property

app\app.component.html
-----
<table border="1px">
    <tr>
        <td>
            第一行
        </td>
        <td>
            第二行
        </td>
    </tr>
    <tr>
        <td colSpan={{1+1}}>
            12345
        </td>
    </tr>
</table>

顯示
https://ithelp.ithome.com.tw/upload/images/20181020/20107754m1UV3FI2fh.png

範例三:利用 .attr 去綁定回 html attribute 的值

app\app.component.html
-----
<table border="1px">
    <tr>
        <td>
            第一行
        </td>
        <td>
            第二行
        </td>
    </tr>
    <tr>
        <td [attr.colspan]="1+1">
            12345
        </td>
    </tr>
</table>

顯示
https://ithelp.ithome.com.tw/upload/images/20181020/201077540ydsxvNpaS.png


上一篇
DAY9-Angular6之data binding-Property和Event
下一篇
DAY11-Angular6之data binding-Class
系列文
Angular初期筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言