angular4筆記系列以內置指令

內置指令

內置屬性型指令

屬性型指令會監聽和修改其它HTML元素或組件的行爲、元素屬性(Attribute)、DOM屬性(Property)。javascript

NgClass

形式:[ngClass]="statement"
經過綁定到NgClass,能夠同時添加或移除多個類。java

setCurrentClasses() {
  this.currentClasses =  {
    'saveable': this.canSave,
    'modified': !this.isUnchanged,
    'special':  this.isSpecial
  };
}

<div [ngClass]="currentClasses">This div</div>
NgStyle

形式:[ngStyle]="statement"
NgStyle綁定能夠同時設置多個內聯樣式。app

setCurrentStyles() {
  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</div>
NgModel

形式:[(ngModel)]="statement"
使用[(ngModel)]雙向綁定到表單元素。this

<input [(ngModel)]="currentHero.name">
使用 ngModel 時須要 FormsModule

內置結構型指令

NgIf

形式:*ngIf="statement"雙向綁定

<app-hero-detail *ngIf="isActive"></app-hero-detail>
NgFor

形式:*ngFor="statement"code

<div *ngFor="let hero of heroes">{{hero.name}}</div>
NgSwitch

形式:[ngSwitch]="statement"orm

<div [ngSwitch]="currentHero.emotion">
  <app-happy-hero *ngSwitchCase="'happy'" [hero]="currentHero"></app-happy-hero>
  <app-sad-hero *ngSwitchCase="'sad'" [hero]="currentHero"></app-sad-hero>
  <app-unknown-hero *ngSwitchDefault [hero]="currentHero"></app-unknown-hero>
</div>
NgSwitch實際上包括三個相互協做的指令:NgSwitch、NgSwitchCase 和 NgSwitchDefault

模板引用變量 ( #var )

模板引用變量一般用來引用模板中的某個DOM元素,它還能夠引用Angular組件或指令或Web Component。ip

<input #phone placeholder="phone number">

<button (click)="callPhone(phone.value)">Call</button>
相關文章
相關標籤/搜索