iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 16
1
Modern Web

Angular 8 從推坑到放棄系列 第 16

[Day 15] Day 15 了 深入了解 Directive

透過attribute directive,我們可以自行擴充元件的屬性,讓元件更富有變化.

在 Angular 中,Directive 分成3種:

  • Components:也就是我們之前就介紹過的Angular 畫面組成的基本元件。
  • Structural directives:主要用來改變 DOM 的配置,例如 ngIf 和ngFor,他們會移除或加入某些DOM元素,來讓 DOM 結構產生變化。
  • Attribute directives:用來改變某個 DOM 元素、 Component 甚至是其他 directive 的顯示方式或行為。

建立基本的 屬性 Attribute

透過 directive 我們可以擴充原有的屬性 attribute,來達到擴充原有的DOM element、Component甚至其他的directive沒有的功能.

將示範透過 directive 來為原來的 p 加上 顏色,並且能透過@Input來傳遞參數給directive,讓設定更加靈活,我們的目標如下圖,每個按鈕可以套用不同的樣式,並且在案下時切換樣式,都只由一個directive搭配不同的參數來完成,如下:

export class BasicHightlightDirective implements OnInit {

  constructor(private elementRef: ElementRef) { }
  ngOnInit() {
    this.elementRef.nativeElement.style.backgroundColor = 'green';
  }
}

然後再要使用的 DOM上透過 selector 使用該 Directive

 <p appBasicHightlight>Style me with basic directive</p>

但上述使用的缺點是,我已經固定要讓使用該 Ditective 的 DOM 顏色改變了,無法動態的修改顏色,可以使用Renderer2 動態調整需要改變的 attribute

使用 Renderer2

export class BetterHighlightDirective implements OnInit {

  constructor(private elRef: ElementRef, private renderer: Renderer2) { }
  ngOnInit() {
    this.renderer.setStyle(this.elRef.nativeElement, 'background-color', 'blue');
  }
}

之後一樣可以在 Html 上使用這個功能

使用 HostEvents

用 HostEvents 監聽來源 Element 的事件

我們可以用 addEventListener 來監聽事件,不過需要注意的是,由於Angular 是一個SPA應用程式,因此 Element 隨時會動態的被產生或消滅,如果我們沒有在Element被消滅時取消監聽的話,長久下來容易造成memory leaks的問題,而 @HostListener 則可以幫我們解決這個問題,在Element被消滅時自動取消監聽!

接下來我們要加入@HostListener,完成最後的目標:在滑鼠按下時改變樣式;這個樣式我們一樣希望可以從@Input來取得,最終的程式碼改寫成:

參考

  1. Angular 4:自訂Directive
  2. Angular.io Structural Directives
  3. [Angular2速成班]使用attribute directive擴充元件屬性

上一篇
[Day 14] 了解 Angular Component 生命週期
下一篇
[Day 16] 了解 相依注入 Service
系列文
Angular 8 從推坑到放棄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
archer
iT邦新手 3 級 ‧ 2019-10-13 13:43:37

請問這一篇 使用 HostEvents 是否沒有完成結尾,
因為程式碼沒有看到有出來

我要留言

立即登入留言