1.插值表達(dá)式 (Interpolation) {{...}}
<p>The sum of 1 + 1 is {{1 + 1}}</p>
2.表達(dá)式上下文 (Expression context)
{{title}}
<span [hidden]="isUnchanged">changed</span>
二.綁定語(yǔ)法
綁定的類型可以根據(jù)數(shù)據(jù)流的方向分成三類:
- 從數(shù)據(jù)源到視圖(source-to-view)
- 從視圖到數(shù)據(jù)源(view-to-source)
- 雙向的從視圖到數(shù)據(jù)源再到視圖(view-to-source-to-view)。
單向 source-to-view
語(yǔ)法 綁定類型
{{expression}} 插值表達(dá)式
[target]="expression" / bind-target="expression" Property, Attribute 類樣式
單向 view-to-source
語(yǔ)法 綁定類型
(target)="statement" / on-target="statement" 事件
雙向
語(yǔ)法 綁定類型
[(target)]="expression" / bindon-target="expression" 雙向
綁定類型(插值表達(dá)式除外)有一個(gè)目標(biāo)名致板,它位于等號(hào)左邊辙培,它是 Property 的名字(注意它不是 Attribute 的名字)咸灿。
綁定目標(biāo) (Binding targets)
Property 綁定類型
目標(biāo) | 范例 |
---|---|
Element property | <img [src]="heroImageUrl"> |
Component property | <hero-detail [hero]="currentHero"></hero-detail> |
Directive property | <div [ngClass]="{special: isSpecial}"></div> |
事件綁定類型
目標(biāo) | 范例 |
---|---|
Element event | <button (click)="onSave()">Save</button> |
Component event | <hero-detail (deleteRequest)="deleteHero()"></hero-detail> |
Directive event | <div (myClick)="clicked=$event" clickable>click me</div> |
雙向綁定類型
目標(biāo) | 范例 |
---|---|
Event and property | <input [(ngModel)]="name"> |
Attribute 綁定類型
目標(biāo) | 范例 |
---|---|
Attribute(例外情況) | <button [attr.aria-label]="help">help</button> |
CSS 類綁定類型
目標(biāo) | 范例 |
---|---|
class property | <div [class.special]="isSpecial">Special</div> |
樣式綁定類型
目標(biāo) | 范例 |
---|---|
style property | <button [style.color]="isSpecial ? 'red' : 'green'"> |
屬性綁定 (Property binding) [property]
<img [src]="heroImageUrl">
上例說明:image 元素的 src 屬性會(huì)被綁定到組件的 heroImageUrl 屬性上容劳。
綁定目標(biāo)
兩種寫法:
<img [src]="heroImageUrl">
![](heroImageUrl)
三.內(nèi)置指令
常見的內(nèi)置屬性型指令:
- NgClass 添加或移除一組CSS類
- NgStyle 添加或移除一組CSS樣式
- NgModel 雙向綁定到 HTML 表單元素
NgClass
示例:組件方法 setCurrentClasses 可以把組件的屬性 currentClasses 設(shè)置為一個(gè)對(duì)象攻走,它將會(huì)根據(jù)三個(gè)其它組件的狀態(tài)為 true 或 false 而添加或移除三個(gè)類
currentClasses: {};
setCurrentClasses() {
this.currentClasses = {
saveable: this.canSave,
modified: !this.isUnchanged,
special: this.isSpecial
};
}
把 ngClass 屬性綁定到 currentClasses,根據(jù)它來設(shè)置此元素的 CSS 類:
<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special</div>
NgStyle
ngStyle 需要綁定到一個(gè) key:value 控制對(duì)象宾抓。 對(duì)象的每個(gè) key 是樣式名抑月,它的 value 是能用于這個(gè)樣式的任何值树叽。
currentStyles: {};
setCurrentStyles() {
// CSS styles: set per current state of component properties
this.currentStyles = {
'font-style': this.canSave ? 'italic' : 'normal',
'font-weight': !this.isUnchanged ? 'bold' : 'normal',
'font-size': this.isSpecial ? '24px' : '12px'
};
}
<div [ngStyle]="currentStyles">
This div is initially italic, normal weight, and extra large (24px).
</div>
NgModel
要使用 ngModel 需要導(dǎo)入 FormsModule 模塊。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // <--- JavaScript import from Angular
/* Other imports */
@NgModule({
imports: [
BrowserModule,
FormsModule // <--- import into the NgModule
],
/* Other module metadata */
})
export class AppModule { }
使用 ngModel 實(shí)現(xiàn)雙向數(shù)據(jù)綁定谦絮。
<input [(ngModel)]="currentHero.name">
該語(yǔ)句實(shí)際上隱藏了其實(shí)現(xiàn)細(xì)節(jié):
<input [ngModel]="currentHero.name"
(ngModelChange)="currentHero.name=$event">
如果需要做一些不同的處理题诵,就不能使用 [(ngModel)] 語(yǔ)法,而應(yīng)寫成擴(kuò)展的方式:
<input [ngModel]="currentHero.name"
(ngModelChange)="setUppercaseName($event)">
ngModel
指令只能用在支持 ControlValueAccessor 的元素上层皱。
四. 內(nèi)置結(jié)構(gòu)型指令
常見的內(nèi)置結(jié)構(gòu)型指令:
- NgIf
- NgFor
- NgSwitch
NgIf
<hero-detail *ngIf="isActive"></hero-detail>
別忘了 ngIf 前面的星號(hào)( * )性锭。
NgFor
<div *ngFor="let hero of heroes">{{hero.name}}</div>
NgSwitch
NgSwitch 由三個(gè)指令組成:
- 屬性型指令 NgSwitch
- 結(jié)構(gòu)型指令 NgSwitchCase
- 結(jié)構(gòu)型指令 NgSwitchDefault
<div [ngSwitch]="currentHero.emotion">
<happy-hero *ngSwitchCase="'happy'" [hero]="currentHero"></happy-hero>
<sad-hero *ngSwitchCase="'sad'" [hero]="currentHero"></sad-hero>
<confused-hero *ngSwitchCase="'confused'" [hero]="currentHero"></confused-hero>
<unknown-hero *ngSwitchDefault [hero]="currentHero"></unknown-hero>
</div>
模板引用變量
使用井號(hào) # (或 ref-)來聲明一個(gè)模板引用變量。The#phone declares a phone variable on an <input> element.
<input #phone placeholder="phone number">
或者寫成
<input ref-phone placeholder="phone number">
輸入輸出屬性 @Input 和 @Output
聲明輸入和輸出屬性(目標(biāo)屬性必須被顯式的標(biāo)記為輸入或輸出叫胖。)
HeroDetailComponent.hero 是屬性綁定的目標(biāo)草冈。 HeroDetailComponent.deleteRequest 是事件綁定的目標(biāo)。
<hero-detail [hero]="currentHero" (deleteRequest)="deleteHero($event)">
</hero-detail>
方法1:使用裝飾器 @Input() 和 @Output()瓮增。
@Input() hero: Hero;
@Output() deleteRequest = new EventEmitter<Hero>();
方法2:通過元數(shù)據(jù)數(shù)組怎棱。
@Component({
inputs: ['hero'],
outputs: ['deleteRequest'],
})
兩種方法不可同時(shí)使用。
給輸入輸出屬性起別名
方法1:把別名傳進(jìn) @Input / @Output 裝飾器绷跑,就可以為屬性指定別名:
@Output('myClick') clicks = new EventEmitter<string>(); // @Output(alias) propertyName = ...
方法2:在 inputs 和 outputs 數(shù)組中為屬性指定別名蹄殃。 語(yǔ)法(屬性名:別名)
@Directive({
outputs: ['clicks:myClick'] // propertyName:alias
})
模板表達(dá)式操作符
管道操作符 |
管道是一個(gè)簡(jiǎn)單的函數(shù),它接受一個(gè)輸入值你踩,并返回轉(zhuǎn)換結(jié)果诅岩。
<div>Title through uppercase pipe: {{title | uppercase}}</div>
還能對(duì)管道使用參數(shù):
<div>Birthdate: {{currentHero?.birthdate | date:'longDate'}}</div>
安全導(dǎo)航操作符 ( ?. ) 和空屬性路徑
Angular 的安全導(dǎo)航操作符 (?.) 用來保護(hù)出現(xiàn)在屬性路徑中 null 和 undefined 值。示例:
The current hero's name is {{currentHero?.name}}
說明:當(dāng) currentHero 為空時(shí)带膜,保護(hù)視圖渲染器吩谦,讓它免于失敗。