Skip to content

Directives#

  1. components
    • component and template
  2. structural directives
    • 改變 view 的結構
    • ngFor、ngIf
  3. attribute directives
    • 改變 Element、component 或其他 directive 的外觀或行為
    • ngStyle、ngClass

Structural Directives (結構型指令)#

  • Angular 使用結構型指令操作DOM
  • 具有重塑DOM結構的能力 → 新增、移除或是維護元素
  • 使用 * 為字首

    • *ngFor: 重複顯示每一個單項

      *ngFor = "let item of items"
      
      • 提供 index 屬性 → 以0為開始的索引
      • 提供 boolean 屬性

        • first、last: 首筆或是尾筆為 true
        • evne、odd: 偶數或是基數時為 true
        *ngFor = "let item of collection; let i = index; let o = odd"
        
    • *ngIf: 顯示項目,條件不符整個元素不存在

      *ngIf = "collectino.length > 3"
      
      • 使用 else 時要搭配 ng-template 使用

        *ngIf = "collection.length > 3; else noMember"
        <ng-template #noMember>
            There is no member
        </ng-template>
        
        • Angular 使用 # 來識別元素項目
    • *ngSwitch: 類似JS的switch,只會有一個被顯示

      • 搭配 ngSwitchCasengSwitchDefault