Angular語法(三)——數據綁定


綁定類型

綁定類型可以按照數據流的方向分為三類:從源到視圖,從視圖到源,以及雙向序列
1

示例

<!-- Bind button disabled state to `isUnchanged` property --> <button [disabled]="isUnchanged">Save</button>

綁定對象

1

Property binding

<img [src]="heroImageUrl"> <img bind-src="heroImageUrl"> <div [ngClass]="classes">[ngClass] binding to the classes property</div>

不要忘記方括號

正確的寫法

<app-hero-detail [hero]="currentHero"></app-hero-detail>

錯誤的寫法

<!-- ERROR: HeroDetailComponent.hero expects a  Hero object, not the string "currentHero" --> <app-hero-detail hero="currentHero"></app-hero-detail>

HeroDetail組件的hero屬性需要一個Hero對象,這正是您在屬性綁定中發送的內容:括號告訴Angular評估模板表達式。
如果省略方括號,Angular會將該字符串視為常量並使用該字符串初始化目標屬性。

屬性綁定還是插值?

下面寫法等效

<p><img src="{{heroImageUrl}}"> is the <i>interpolated</i> image.</p> <p><img [src]="heroImageUrl"> is the <i>property bound</i> image.</p> <p><span>"{{title}}" is the <i>interpolated</i> title.</span></p> <p>"<span [innerHTML]="title"></span>" is the <i>property bound</i> title.</p>

Attribute, class, and style bindings

Attribute binding

錯誤的寫法

<tr><td colspan="{{1 + 1}}">Three-Four</td></tr>

報錯

Template parse errors:
Can't bind to 'colspan' since it isn't a known native property

正確的寫法

<!-- expression calculates colspan=2 --> <tr><td [attr.colspan]="1 + 1">One-Two</td></tr>

Class binding

不使用bind

<div class="bad curly special">Bad curly special</div>

使用bind

<!-- reset/override all class names with a binding --> <div class="bad curly special" [class]="badCurly">Bad curly</div>

Style binding

Style binding語法類似於Property binding。 代替括號內的元素屬性,從前綴樣式開始,后跟一個點(.)和一個CSS樣式屬性的名稱:[style.style-property]

<button [style.color]="isSpecial ? 'red': 'green'">Red</button> <button [style.background-color]="canSave ? 'cyan': 'grey'" >Save</button>

一些樣式有一個單位擴展名。

<button [style.font-size.em]="isSpecial ? 3 : 1" >Big</button> <button [style.font-size.%]="!isSpecial ? 150 : 50" >Small</button>

Event binding

兩種寫法

<button (click)="onSave()">Save</button> <button on-click="onSave()">On Save</button>
<input [value]="currentHero.name" (input)="currentHero.name=$event.target.value" >

還可以自定義Event

Two-way binding ( [(...)] )

Angular為雙向綁定提供了一種特殊的雙向數據綁定語法,[(x)]。 [(x)]語法將屬性綁定的括號[x]與事件綁定的括號(x)組合在一起。

[( )] = BANANA IN A BOX
香蕉在一個盒子里
在盒子中形象化一個香蕉,記住圓括號在括號內。

示例

<app-sizer [(size)]="fontSizePx"></app-sizer>
<div [style.font-size.px]="fontSizePx">Resizable Text</div>

雙向綁定語法實際上只是語法綁定和事件綁定的語法糖。

<app-sizer [size]="fontSizePx" (sizeChange)="fontSizePx=$event"></app-sizer>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM