選單
GSS 技術部落格
在這個園地裡我們將從技術、專案管理、客戶對談面和大家分享我們多年的經驗,希望大家不管是喜歡或是有意見,都可以回饋給我們,讓我們有機會和大家對話並一起成長!
若有任何問題請來信:gss_crm@gss.com.tw
3 分鐘閱讀時間 (563 個字)

Angular # 37 - Directives and Pipes[3]

shutterstock_198004562
  • Structural Directives

    • Structural directives 使得我們可以操作整個 DOM tree, 而非只是元素本身(e.g. 依條件植入或移除整塊 div)

      • 基本上 NgIf, NgFor, NgSwitch 應該就可以處理大部份需要 structural directives 的情境

      • 不過既然要學習,還是建一個 attribute directive 來玩玩,這個 directive 會延遲元件的顯示

          ng g d directives/delay
      • 接著實作 delay.directive.ts 的內容如下:

          import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
        
          @Directive({
            selector: '[delay]'
          })
          export class DelayDirective {
        
            @Input() set delay(ms: number) {
              setTimeout(() => {
                this.viewContainer.createEmbeddedView(this.templateRef);
              }, ms);
            }
            constructor(
              private templateRef: TemplateRef<any>,
              private viewContainer: ViewContainerRef
            ) { }
        
          }
        • 首先 import 需要的元件
        • 接著在掛上 @Directive 時定義 selectordelay
        • 建構子中注入了指向元素所在的 template 的參考(TemplateRef) 以及容納該元素的 view(ViewContainerRef) 的參考
        • 當 Angular 在渲染 structural directive 的時候,它會產一個內嵌的 view(embeddedView),讓 directive 決定可以放什麼東西到 view container
        • 透過 ViewContainerRef 可以參考到那個 view container,並在其內建立任意數量的 view
        • 在 view container 被渲染後,template 會被抽出並從頁面上移除,但會留下一個 TemplateRef 給我們操作
        • 這代表 directive 可以決定何時透過呼叫方法渲染元素
        • delay 這個方法是個 javascript setter, 同時也是一個 @input 屬性用來接收 setTimeout 需要的 interval
        • 承上,也正是在這個方法中,透過 ViewContainerRef 建立了一個 embedded view,並將被裝飾的 component 透過 TemplateRef 加到 view 中
      • 在使用 structural directive, 必須加上 *(星號), 像是 *ngIf, *ngFor, and ... *delay="1000"

      • 定義好 Directive,來調整一下 DashboardComponent 的 template 如下:

          <div class="mdl-cell mdl-cell--3-col" *ngFor="let stock of stocks;index as i">
              <summary [stock]="stock" *delay="i * 100" cardTone></summary>
        </div>
        • *ngFor 現在有一個計步器 i, 可以取得現在跑到哪圈了
        • ng serve 囉!看看那華麗的 delay 如何延持顯示
    • Structural directives 很不一樣

      • 它們是直接操控 view 而非已經被渲染的元素本身
      • 要用這種 Directive 前建議還是看一下官方文件,因為它相對複雜許多,且…應該是不太會用到才對
  • 小結:

    • Directive 到此告一段落
      • 此篇的重點在如何透過 ViewContainerRef 與 TemplateRef 來定義 Structural directive
      • 大部份的情境都可以透過 *NgFor *NgIf *NgSwitch 處理,所以要定義這類的 directive 之前不妨先思考看看
Angular #38 - Directives and Pipes[4]
Angular #36 - Directives and Pipes[2]

相關文章

 

評論

尚無評論
已經注冊了? 這裡登入
Guest
2024/05/10, 週五

Captcha 圖像