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

Angular #36 - Directives and Pipes[2]

shutterstock_198004562
  • 前一篇我們定義了一個 Directive cardType,不過它是被用在 div 這個 HTML 元素上
    • 如果我們想在第三方開發的 Component 上加上 Directive 該怎麼做?
      • 假設 SummaryCard 就是那個第三方的 Component, 而且我們想在它預設的功能上加上一些屬性或行為
      • 首先我們先建立一個新的 directive
          ng g d directives/card-hover
      • 接著定義 directive 的內容
          import { Directive, ElementRef, OnInit, HostListener } from '@angular/core';
          @Directive({
            selector: '[cardHover]'
          })
          export class CardHoverDirective implements OnInit {
            card: any;
            constructor(private el: ElementRef) { }
            ngOnInit() {
              this.card = this.el.nativeElement.querySelector('.mdl-card');
              if (this.card.classList.contains('increase')) {
                this.card.style.backgroundColor = 'rgb(63,81,181)';
              } else if (this.card.classList.contains('decrease')) {
                this.card.style.backgroundColor = 'rgb(255,171,64)';
              } else {
                this.card.style.backgroundColor = '';
              }
            }
            @HostListener('mouseover') onMouseOver() {
              this.card.style.boxShadow = '2px 2px 1px #999';
              this.card.style.top = '-2px';
            }
            @HostListener('mouseout') onMouseOut() {
              this.card.style.boxShadow = '';
              this.card.style.top = '';
            }
          }
        • 跟前面的 Directive 很相似,這裡定義了三個重要的方法
          • ngOnInit: 在 Component 初始化完所有屬性後調整其 backgroundColor
          • onMouseOver: 加上 mouseover 事件發生時調整 boxShadowtop 的屬性質
          • onMouseOut,同上,但是是針對 mouseout 事件
        • @HostListener: 這是定義所有需要讓 Directive 監聽的事件的 Decorator,傳入的參數自然是事件的名稱
      • 接著調整一下 DashboardComponent 的 template
          <summary [stock]="stock" cardHover></summary>
        • 重新 ng serve 啟動測試 server 後,可以看到既有的元件(SummaryCard) 只要掛上 cardHover 就會加上額外的功能(以此例是會有浮動的視覺效果/背景色的切換)
        • 當然這個 Directive 也可以定義 @Input 的屬性,再依傳入的值來作後續的處理
      • 看到這裡你或許會想,為什麼不用 CSS 就好了?
        • 當然可以用 CSS,如果情境夠單純的話
        • 用 Javascript 可以取得整個 DOM 相關的資訊,可以作更複雜的處理,所以要用哪一種就看當下的情境
  • 小結:
    • 此篇針對既有的 Component 透過 Directive 來修改行為
      • 如果可以的話 Directive 當然是愈通用愈好
      • 但如果情境就是需要對某種 Component 有某程度上的耦合,那也無可厚非
      • 下一篇將探討 Structural Directive
Angular # 37 - Directives and Pipes[3]
Angular #35 - Directives and Pipes[1]

相關文章

 

評論

尚無評論
已經注冊了? 這裡登入
Guest
2025/06/09, 週一

Captcha 圖像