Angular 9 implement a hover effect with directives


Directive 指令

指令(Directive)概覽
在 Angular 中有三種類型的指令:
1.元件(Components) — 擁有範本的指令。最常用的那一種。
2.結構型指令(Structural Directives) — 透過新增和移除 DOM 元素改變 DOM 佈局的指令。例如 NgFor 和 NgIf。
3.屬性型指令(Attribute directives) — 改變元素、元件或其它指令的外觀和行為的指令。例如,內建的 NgStyle 指令。

俗話說,Directive 有三種:元件、結構、屬性。
元件、結構不用不行,但屬性...這個之前好像都沒什麼機會用。這一篇記錄一下實作改變按鈕的屬性指令。

Attribute directives

首先建立一個 hover directive ng generate directive hover

@Directive({
  selector: '[appHover]'
})

簡單來說這邊的 selector 對應 html 標籤上的屬性。
針對想要產生屬性變化的元素加上 appHover:

<button appHover class="btn btn-block">
    Login
</button>

接著用 ElementRef, HostListener 來操作 DOM 元素、監聽事件

import { Directive, ElementRef, Renderer2, HostListener, HostBinding,} from '@angular/core';

@Directive({
  selector: '[appHover]'
})
export class HoverDirective {
  defaultColor='#da9a8a'; //$secondary
  hoverColor='#73c2c1'; //$tertiary

  constructor(
    private elementRef:ElementRef, 
    private renderer:Renderer2
  ) { }

    ngOnInit(){
      this.color = this.defaultColor;
    }

    @HostBinding('style.background-color') color:string = this.defaultColor;

    @HostListener('mouseenter') mouseover(){
      this.renderer.setStyle(this.elementRef.nativeElement, 'background-color', this.hoverColor ); 
    }

    @HostListener('mouseleave') mouseleave(){
      this.renderer.setStyle(this.elementRef.nativeElement, 'background-color', this.defaultColor );
    }

}

到這邊就是跟著官方文件做。這樣的好處是透過 Attribute directives 將 javascript 和 css 模組化。
但有一個問題是,我要的配色已經寫在 _vasiable.scss 裡,如果我的配色改變,我就必須要修改許多個 Attribute directives,原本想抓 _vasiable.scss 來用,但又覺得這樣很亂。
後來是做一個 directive 常數。
但這樣我就有一個 scss 常數,一個 directive 常數。感覺也是不對勁。不知道怎摸辦了。

export const colors = 
{  
    "$primary": "#7bb1eb",
    "$secondary": "#da9a8a",
    "$tertiary": "#73c2c1",
}

hover.directive

  defaultColor= colors.$secondary;
  hoverColor= colors.$tertiary;

參考








你可能感興趣的文章

CSS - Flexbox

CSS - Flexbox

[Swift 學習筆記] Closure : Inline function process

[Swift 學習筆記] Closure : Inline function process

使用上聯想語法

使用上聯想語法






留言討論