如果你還沒看過上一篇內嵌繫結的話,可以回去看看。
Angular 上可以將資料繫結到頁面元素的屬性上,而在網頁設計當中有兩種屬性:一種是 Property ,一種是 Attribute。
Property 是 DOM 操作下的屬性,是瀏覽器在載入網頁時建立的 DOM 節點當中的屬性,可以從瀏覽器的開發者模式(F12)當中看到。
Attribute 是 HTML 元素標籤當中的屬性,例如下面一段 HTML:
<img src="https://" alt="pic" />
img、src 及 alt 都是 Attribute,像是其他 href 那些也都是。
以上兩種屬性並不完全對應,而屬性繫結操作的是 Propertry 並非 Attribute,像是下面的範例使用的 disabled 屬性並不是 Attribute,如果繫結要使用 Attribute 屬性的話,要改成 [attr.AttributeName] 的方式使用。
屬性繫結使用 [ ] 將屬性名稱包起來,直接看範例。我們實作一個按鈕可不可以被按下的範例。
<button type="button" [disabled]="state===true">我是按鈕,你按得到嗎?</button>
這個按鈕是否可以被按,取決於 disabled 這個屬性是否存在(也就是右側的條件是否成立),如果要使用 Attribute 屬性來繫結的話可以這樣寫:
<button type="button" [attr.disabled]="state===true ? 'disabled' : null">我是按鈕,你按得到嗎?</button>
大多數的情況下不會使用 Attritube 的寫法。
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
state = false;
}
做的事情很簡單,設定 state ,state 表示按鈕是否被禁止使用,如果這樣直接執行 ng serve 會發現按鈕可以按。
改成 true 就不能按了!下一篇會介紹事件繫結。